Get element node at caret position (in contentEditable)

后端 未结 1 1292
北海茫月
北海茫月 2020-11-29 07:00

Let\'s say I have some HTML code like this:


   

Some heading text here

Some text here&l

相关标签:
1条回答
  • 2020-11-29 07:53

    Firstly, think about why you're doing this. If you're trying to stop users from editing certain elements, just set contenteditable to false on those elements.

    However, it is possible to do what you ask. The code below works in Safari 4 and will return the node the selection is anchored in (i.e. where the user started to select, selecting "backwards" will return the end instead of the start) – if you want the element type as a string, just get the nodeName property of the returned node. This works for zero-length selections as well (i.e. just a caret position).

    function getSelectionStart() {
       var node = document.getSelection().anchorNode;
       return (node.nodeType == 3 ? node.parentNode : node);
    }
    
    0 讨论(0)
提交回复
热议问题