selectionStart和selectionEnd在contenteditable元素中

时间:2013-10-10 06:35:46

标签: jquery textarea selection contenteditable

我一直在努力克服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?

3 个答案:

答案 0 :(得分: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>

我在jsfiddler中做了这个例子,看到了 enter link description here

答案 1 :(得分:1)

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

var sel = document.getSelection();
node.value = node.value.slice(0, sel.baseOffset - step) + value + node.value.slice(sel.extentOffset);

答案 2 :(得分:0)

此答案使用的是Selection#modify,它是非标准的,但至少我建议您使用“ insertText”命令:

function replaceVal(val, step) {
  var selection = window.getSelection();
  for (var i = 0; i < step; i += 1) {
    selection.modify('extend', 'backward', 'character');
  }
  document.execCommand('insertText', false, val);
}
<label for="editable">Editable:</label>
<div contenteditable="true" id="editable">Test test test</div>
<label for="step">Step:</label>
<input type="number" id="step" name="step" min="0" step="1" value="0" />
<button onClick="replaceVal('insertion', Number(document.getElementById('step').value))">Get text</button>

相关问题