美文网首页前端
vue.js表单输入在光标处上屏显示关键词

vue.js表单输入在光标处上屏显示关键词

作者: 不忘初心_6b23 | 来源:发表于2021-02-05 10:28 被阅读0次

需求:
备注文本框可以输入文字等,限制最大100字符。可以在光标处点击快捷标签插入指定内容

先上html片段

<el-form-item label="备注" prop="remark">
        <el-input
          id="textarea"
          type="textarea"
          placeholder="请输入内容"
          v-model="value.remark"
          maxlength="100"
          :disabled="$route.query.pageFrom=='visitPreview'"
          rows="4"
          show-word-limit
        >
        </el-input>
        <div>
          <span v-for="(item,idx) in quickRemarkList" :key="item.name" class="remark">
            <el-button
              type="text"
              @click="inputQuictRemark(item.name)">
              {{item.name}}
            </el-button>
          </span>
        </div>
      </el-form-item>

实现部分

/*输入快捷remark*/
    inputQuictRemark(val){
      let elInput = document.getElementById('textarea'); 
      let startPos = elInput.selectionStart;
      let endPos = elInput.selectionEnd;
      if (startPos === undefined || endPos === undefined) return
      let addStr = ' ' +val+ ' '
      if(addStr.length + this.value.remark?.length > 100){
        this.$message.closeAll();
        this.$message.error('已达到可填写上限')
        return
      }
      let txt = elInput.value;
      let result = txt.substring(0, startPos) + ' ' + val + ' ' + txt.substring(endPos)
      elInput.value = result;
      this.value.remark  = result;
      elInput.focus();
      elInput.selectionStart = startPos + val.length + 2;
      elInput.selectionEnd = startPos + val.length + 2;
      this.$forceUpdate()
    },

相关文章

网友评论

    本文标题:vue.js表单输入在光标处上屏显示关键词

    本文链接:https://www.haomeiwen.com/subject/vtgbtltx.html