selectionStart和selectionEnd在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; //... } 

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

试试这个,它返回所选的文本,无论它是否是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); } } } 
 
Test Example Microsoft T-shirt box