简体   繁体   English

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

[英]How can I get the element the caret is in with Javascript, when using contentEditable?

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". 现在,插入符号(闪烁的光标)在H1元素内部闪烁,让我们在单词“heading”中说。 How can I get the name of the element the caret is in with JavaScript? 如何使用JavaScript获取插入符号元素的名称? Here I would like to get "h1". 在这里,我想得到“h1”。

This needs to work only in WebKit (it's embedded in an application). 这只需要在WebKit中工作(它嵌入在应用程序中)。 It should preferably also work for selections. 它最好也适用于选择。

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 (ie 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. 下面的代码在Safari 4中工作,并将返回选择所锚定的节点(即用户开始选择的位置 ,选择“向后”将返回结束而不是开始) - 如果您希望元素类型为字符串,只需获取返回节点的nodeName属性。 This works for zero-length selections as well (ie just a caret position). 这也适用于零长度选择(即只是一个插入位置)。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用JavaScript动态添加数据时,如何在可编辑内容的div文本末尾获得插入符号位置? - How to get the caret position at the end of the text of a contenteditable div when the data is added dynamically using Javascript? 如何从 contenteditable 获得“删除插入符号位置”? - How can I get the "drop caret position" from contenteditable? 如何获得内容可编辑的插入符号位置 - How can I get the caret position on a contenteditable <button> 如何检查{}中是否包含可编辑的插入符号 - How can I check if contenteditable caret is inside { } Javascript - 在[contenteditable]的子元素中获取插入符号后面的元素 - Javascript - Get element behind caret in child elements of [contenteditable] javascript:将插入符号移动到元素的结尾(div与contenteditable) - javascript: move caret to end of element (div with contenteditable) Javascript:获取内容中的文本可编辑到插入符号 - Javascript: Get text in a contenteditable up to the caret 如何获得一个可疑的html元素的光标行号? - How can i get the cursor line number of a contenteditable html element? 如何保持插入符号在 contenteditable 元素中的位置 - How to keep the position of the caret in contenteditable element 如何在保持插入记号x偏移的同时在可内容编辑的列表项之间(不同缩进量)移动插入记号? - How can I move the caret between contenteditable list items (of varying indents) while maintaining caret x offset?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM