selectionStart和selectionEnd在contenteditable元素中

问题描述 投票:15回答:1

我一直在努力使用textarea的selectionStart和selectionEnd属性来使它们与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;
  //...
}

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

jquery textarea selection contenteditable
1个回答
4
投票

试试这个,它返回所选的文本,无论它是否是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);
                }
            }
        }
<div>Test Example Microsoft T-shirt box</div>
<button onClick="GetSelectedText()">Get text</button>

我在jsfiddle中做了这个例子,看看qazxsw poi

© www.soinside.com 2019 - 2024. All rights reserved.