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

发布于 2024-07-29 16:13:36 字数 406 浏览 2 评论 0原文

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

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

现在插入符号(闪烁的光标)在

元素内闪烁,让我们在单词 "|heading"

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

墨洒年华 2024-08-05 16:13:36

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

但是,可以按照您的要求进行操作。 下面的代码适用于 Safari 4,并将返回选择项锚定的节点(即用户开始选择的位置,选择“向后”将返回结束而不是开始) - 如果您愿意元素类型为字符串,只需获取返回节点的nodeName属性即可。 这也适用于零长度选择(即仅插入符号位置)。

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

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文