需求:將textarea與span標簽組合,點擊標簽自動填入標簽文本內容,再次點擊刪除標簽文本對應內容

原理:點擊標簽時,將標簽內容作為參數,將內容拼接在textarea的value后面,再次點擊標簽,使用js的replace替換(這里只能替換找到的第一個與標簽內容相同的值)
實現代碼如下:
<template> <div class="relative-element"> <textarea v-model="myForm.remark" type="textarea" :maxlength="300" placeholder="請輸入備注,300字以內"></textarea> <div class="bottom-labels" ref="remarkLabels"> <span title="九零后" @click.stop="autoFillIn('九零后', $event)">九零后</span> <span title="小說迷" @click.stop="autoFillIn('小說迷', $event)">小說迷</span> <span title="天真無邪" @click.stop="autoFillIn('天真無邪', $event)">天真無邪</span> <span title="可愛迷人" @click.stop="autoFillIn('可愛迷人', $event)">可愛迷人</span> <span title="帥氣逼人" @click.stop="autoFillIn('帥氣逼人', $event)">帥氣逼人</span> </div> </div> </template> <script> export default { data() { return { myForm: { remark: '小說迷 ' } } }, mounted() { this.initLabelsCheck(this.myForm.remark); }, methods: { // textarea初始化(標簽根據內容是否選中) initLabelsCheck(remark) { if(remark){ let remarkArr = remark.split(" "); if(remarkArr.length > 0 && this.$refs.remarkLabels){ let labels = this.$refs.remarkLabels.querySelectorAll("span"); for(let i=0; i<remarkArr.length; i++){ for(let l=0; l<labels.length; l++) { if(remarkArr[i].trim()!=='' && remarkArr[i] === labels[l].getAttribute("title")){ labels[l].classList.add('active'); } } } } } }, // textarea點擊標簽自動填入 autoFillIn(text, event){ let target = event.target; if(target.classList.contains("active")){ // 再次點擊刪除 text = text + " "; this.myForm.remark = this.myForm.remark.replace(text, ''); } else { if(this.myForm.remark.length === 0){ this.myForm.remark += text + " "; } else { this.myForm.remark = this.myForm.remark.trim() + " " + text + " "; } } target.classList.toggle("active"); } } } </script> <style lang="scss" scoped> .relative-element { position: relative; margin: 30px 40px; width: 400px; textarea { display: block; padding: 5px 15px; width: 100%; height: 150px; resize: vertical; line-height: 1.5; box-sizing: border-box; font-size: inherit; color: #606266; background-color: #fff; border: 1px solid #dcdfe6; border-radius: 4px; transition: border-color .2s cubic-bezier(.645,.045,.355,1); } .bottom-labels { position: absolute; left: 10px; right: 10px; bottom: 3px; line-height: 18px; background-color: #fff; user-select: none; span { display: inline-block; margin: 0 3px; padding: 0 6px; font-size: 12px; background-color: #f3f3f3; vertical-align: middle; &:hover { cursor: pointer; } &.active { color: #29e; } } } } </style>
