【问题标题】:Inserting text at the cursor point - currently inserting into the clicked element not text field在光标点插入文本 - 当前插入单击的元素而不是文本字段
【发布时间】:2016-03-18 20:29:56
【问题描述】:

找到这个函数:

function insertTextAtCursor(text) {
    var sel, range, html;
    sel = window.getSelection();
    range = sel.getRangeAt(0);
    range.deleteContents();
    var textNode = document.createTextNode(text);
    range.insertNode(textNode);
    range.setStartAfter(textNode);
    sel.removeAllRanges();
    sel.addRange(range);
}

我有一个内容可编辑的 div 和一个按钮,用于将图像标签添加到 div 中。

但是,根据小提琴,按钮将文本添加到自身而不是 div。

有什么帮助吗?

https://jsfiddle.net/e859j9an/

【问题讨论】:

  • window.getSelection() 用于从元素中获取选定的文本。由于您的源与选择相同,因此最终会将文本节点附加到相同的元素。您是否只想在单击按钮时将图像标签添加到 div 中?

标签: jquery contenteditable


【解决方案1】:

编辑:当您点击可编辑的 div 时,我找到了一种方法:

See this fiddle

我已经用这段代码更新了你的 JS:

$(function() {
  /* Text editor */   
  $(".custom-text-editor").on('click', function(){
    insertTextAtCursor('this text');
  });   
});

function insertTextAtCursor(text) {
    var sel, range, html;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            range.insertNode( document.createTextNode(text) );
        }
    } else if (document.selection && document.selection.createRange) {
        document.selection.createRange().text = text;
    }
}

我不知道你点击按钮时是否可以在div.custom-text-editor中获得正确的位置..

【讨论】:

  • 嗨,谢谢,不,希望能够简单地在光标处插入文本。使用中等风格的文本编辑器,目前它只是插入文本,但最终将成为图像上传器。
  • 我已经对其进行了编辑,但如果您单击其他按钮而不是单击 div,我怀疑您能否在 contenteditable div 中获得正确的位置
【解决方案2】:

这是因为当你点击另一个元素时,contenteditable div 失去了焦点。

像这样更改您的代码。

$(".custom-text-editor").focus();
$(".insert-image").on('mousedown', function(e){
insertTextAtCursor("this is an image");
return false;
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-20
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多