selectionStart和selectionEnd在contenteditable元素中

Sem*_*ech 20 jquery textarea selection contenteditable

我一直在努力使用textarea 的selectionStartselectionEnd属性来使它们与contenteditable div元素一起工作.我已经在谷歌和SO上检查了很多相关文章,但无济于事.我有类似下面的东西,完全适用于textarea.但我希望这个与满足的div一起工作.

function replaceVal(node, val, step){
    //...
    var cursorLoc =  node.selectionStart;
    node.value = node.value.substring(0, node.selectionStart - step) + value +
    node.value.substring(node.selectionEnd, node.value.length);
    node.scrollTop = scrollTop;
    node.selectionStart = cursorLoc + value.length - step;
    node.selectionEnd = cursorLoc + value.length - step;
  //...
}
Run Code Online (Sandbox Code Playgroud)

如何修改它以便它可以使用contenteditable div元素而不是textarea?

Al *_* Po 8

使用getSelection()方法中的Selection对象来获取contentEditable 元素baseOffsetextentOffset

var sel = document.getSelection();
node.value = node.value.slice(0, sel.baseOffset - step) + value + node.value.slice(sel.extentOffset);
Run Code Online (Sandbox Code Playgroud)


RBo*_*ini 7

尝试此操作,无论是否为contentEditable,它都会返回选定的文本。

function GetSelectedText() {

            if (document.getSelection) {    // all browsers, except IE before version 9
                var sel = document.getSelection();
                    // sel is a string in Firefox and Opera, 
                    // and a selectionRange object in Google Chrome, Safari and IE from version 9
                    // the alert method displays the result of the toString method of the passed object
                alert(sel);
            } 
            else {
                if (document.selection) {   // Internet Explorer before version 9
                    var textRange = document.selection.createRange();
                    alert(textRange.text);
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)
<div>Test Example Microsoft T-shirt box</div>
<button onClick="GetSelectedText()">Get text</button>
Run Code Online (Sandbox Code Playgroud)

我在jsfiddler中创建了此示例,请参见 此处输入链接说明