获取插入标记位置处的元素节点(在contentEditable中)

问题描述:

假设我有一些这样的HTML代码:

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>

现在插入符号(闪烁的光标)在< h1>中闪烁; 元素,比如 | heading

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

如何获取用JavaScript插入符号的元素?在这里,我想获取节点名称: h1

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

这仅需要在WebKit中工作(嵌入到应用程序中)。它最好也应适用于选择。

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

首先,考虑为什么为什么。如果要阻止用户编辑某些元素,只需将 contenteditable 设置为false即可。

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.

但是,可以按照您的要求做。下面的代码在Safari 4中有效,并且将返回所选内容所锚定的节点(即,用户开始选择的位置,选择向后将返回结束而不是开始)–如果需要元素类型为字符串,只需获取返回节点的 nodeName 属性即可。

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