sailei1 / blog

1 stars 0 forks source link

JS 获取 input 光标位置 #92

Closed sailei1 closed 4 years ago

sailei1 commented 4 years ago
<textarea class="content" rows="5" v-model="textConent" placeholder="分享职场动态"  @click="getCursortPosition($event)"/>

getCursortPosition(e){
            let obj=e.target;
            if(!obj){ return}
            var cursorIndex = 0;
            if (document.selection) {
                obj.focus();
                var range = document.selection.createRange();
                range.moveStart('character', -obj.value.length);
                cursorIndex = range.text.length;
            } else if (obj.selectionStart || obj.selectionStart==0) {
                // another support
                cursorIndex = obj.selectionStart;
            }
            this.inputIndex=cursorIndex;
        },
 getBrow(index) {
            // let reg=new RegExp('/(.{'+this.inputIndex+'})/');
            // debugger;
            let text=this.textConent,start=this.inputIndex;
            for (let i in this.faceList) {
                if (index == i) {
                    this.getBrowString = this.faceList[index];
                    if(text) { 
                      //插入表情图片   
                     //str.replace(/(.{1})/, "$1新插入字符串") 正则无效
                        text = text.slice(0, start) + this.getBrowString + text.slice(start);
                    }else{
                        text=this.getBrowString;
                    }
                    break;
                }
            }
            this.textConent=text;

        },