使用contentEditable时,如何使用Javascript获取插入符号元素?

时间:2022-08-25 18:43:09

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

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

<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 name of the element the caret is in with JavaScript? Here I would like to get "h1".

现在,插入符号(闪烁的光标)在H1元素内部闪烁,让我们在单词“heading”中说。如何使用JavaScript获取插入符号元素的名称?在这里,我想得到“h1”。

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

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

1 个解决方案

#1


43  

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.

首先,想想你为什么要这样做。如果您试图阻止用户编辑某些元素,只需在这些元素上将contenteditable设置为false即可。

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).

但是,你可以做你所要求的。下面的代码在Safari 4中工作,并将返回选择所锚定的节点(即用户开始选择的位置,选择“向后”将返回结束而不是开始) - 如果您希望元素类型为字符串,只需获取返回节点的nodeName属性。这也适用于零长度选择(即只是插入位置)。

function getSelectionStart() {
   var node = document.getSelection().anchorNode;
   return (node.nodeType == 3 ? node.parentNode : node);
}

#1


43  

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.

首先,想想你为什么要这样做。如果您试图阻止用户编辑某些元素,只需在这些元素上将contenteditable设置为false即可。

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).

但是,你可以做你所要求的。下面的代码在Safari 4中工作,并将返回选择所锚定的节点(即用户开始选择的位置,选择“向后”将返回结束而不是开始) - 如果您希望元素类型为字符串,只需获取返回节点的nodeName属性。这也适用于零长度选择(即只是插入位置)。

function getSelectionStart() {
   var node = document.getSelection().anchorNode;
   return (node.nodeType == 3 ? node.parentNode : node);
}