Get element node at caret position (in contentEditable)

蹲街弑〆低调 提交于 2020-01-09 03:26:44

问题


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

<body contentEditable="true">
   <h1>Some heading text here</h1>
   <p>Some text here</p>
</body>

Now the caret (the blinking cursor) is blinking inside the <h1> element, let's say in the word "|heading".

How can I get the element the caret is in with JavaScript? Here I would like to get node name: "h1".

This needs to work only in WebKit (it's embedded in an application). It should preferably also work for selections.


回答1:


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);
}


来源:https://stackoverflow.com/questions/1197401/get-element-node-at-caret-position-in-contenteditable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!