在光标位置插入文本,设置光标位置

            <div class="color borderColor pointer" @click="addSymbol('+')">+</div>
            <div class="color borderColor pointer" @click="addSymbol('|')">|</div>
            <div class="color borderColor pointer" @click="addSymbol('()')">( )</div>
 

         
 <el-input style="width: 94%" @blur="blurEvent" size="small" placeholder="多个排除词之间以,隔开,词组之间为“与”关系" :rows="5" type="textarea" v-model="ruleForm.excludeWords"></el-input>


data() { return { blurIndex: null,//记录光标位置 ruleForm: { excludeWords: '' }, } },


methods: {
// 获取光标所在位置的index blurEvent(e) { this.blurIndex = e.srcElement.selectionStart; console.log(e) console.log(e.srcElement) console.log(e.srcElement.selectionStart) //光标所在的位置 }, // 添加符号 addSymbol(symbol){ let index=this.blurIndex let str=this.ruleForm.excludeWords this.ruleForm.excludeWords=str.slice(0, index) + symbol + str.slice(index);      this.blurIndex++ }, }

设置光标位置

      set_text_value_position(obj, spos){
        var tobj = document.getElementById(obj);
        if(spos<0)
          spos = tobj.value.length;
        if(tobj.setSelectionRange){ //兼容火狐,谷歌
          setTimeout(function(){
              tobj.setSelectionRange(spos, spos);
              tobj.focus();}
            ,0);
        }else if(tobj.createTextRange){ //兼容IE
          var rng = tobj.createTextRange();
          rng.move('character', spos);
          rng.select();
        }
      },

调用  参数一:input框dom的id,参数二:位置

        // 调用设置光标位置
        this.set_text_value_position('inputId',5)

 

posted @ 2022-08-15 11:33  从入门到入土  阅读(422)  评论(0编辑  收藏  举报