获取鼠标点击的地方,并插入文本。window.getSelection()

前言:因项目需求,有一个富文本框,点击页面的插入姓名,会在富文本框内的鼠标处,插入姓名。

解决:利用window.getSelection() 来获取富文本框的焦点,并保存下来,在点击插入姓名时,在再那个焦点处插入。

EX:

注:因为项目是vue 写的,所以有些变量需要自己在data 里免定义

在富文本框内点击的时候保存一下焦点   this.sel ;isWang 是判断插入的时候,富文本框内点击一次,只能插一条数据

this.editor.customConfig.onfocus = () => {
    this.sel = window.getSelection();    
    this.range = this.sel.getRangeAt(0);
    this.range.deleteContents();
    this.$set(this.get, 'isWang', true);
};
this.editor.customConfig.onblur = (html) => {
    this.$set(this.get, 'isWang', false);
};

//  插入的方法

insertHtmlAtCaret(html) {
    if (window.getSelection) {
        // IE9 and non-IE
        if (this.sel.getRangeAt && this.sel.rangeCount) {

            // Range.createContextualFragment() would be useful here but is
            // non-standard and not supported in all browsers (IE9, for one)
            var el = document.createElement("div");
            el.innerHTML = html;
            var frag = document.createDocumentFragment(), node, lastNode;
            while ((node = el.firstChild)) {
                lastNode = frag.appendChild(node);
            }
            this.range.insertNode(frag);
            // Preserve the selection
            if (lastNode) {
                this.range = this.range.cloneRange();
                this.range.setStartAfter(lastNode);
                this.range.collapse(true);
                this.sel.removeAllRanges();
                this.sel.addRange(this.range);
            }
        }
    } else if (document.selection && document.selection.type != "Control") {
        // IE < 9
        document.selection.createRange().pasteHTML(html);
    }
},

//  点击插入姓名时插入的方法

insertName() {
    if (!this.get.isWang) {
        return false;
    }
    document.getElementById('editor').focus();
    this.$set(this.insert, 'name', api.getUserName());
    this.insertHtmlAtCaret('<span>' + this.insert.name + '</span>');
},

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值