获取插入符号位置的元素节点(在 contentEditable 中) [英] Get element node at caret position (in contentEditable)

查看:31
本文介绍了获取插入符号位置的元素节点(在 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);
}

这篇关于获取插入符号位置的元素节点(在 contentEditable 中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆