![](/img/trans.png)
[英]How to get the caret position at the end of the text of a contenteditable div when the data is added dynamically using Javascript?
[英]How can I get the element the caret is in with Javascript, when using contentEditable?
假设我有一些像这样的HTML代码:
<body contentEditable="true">
<h1>Some heading text here</h1>
<p>Some text here</p>
</body>
现在,插入符号(闪烁的光标)在H1元素内部闪烁,让我们在单词“heading”中说。 如何使用JavaScript获取插入符号元素的名称? 在这里,我想得到“h1”。
这只需要在WebKit中工作(它嵌入在应用程序中)。 它最好也适用于选择。
首先,想想为什么你这样做。 如果您试图阻止用户编辑某些元素,只需在这些元素上将contenteditable
设置为false即可。
但是,你可以做你所要求的。 下面的代码在Safari 4中工作,并将返回选择所锚定的节点(即用户开始选择的位置 ,选择“向后”将返回结束而不是开始) - 如果您希望元素类型为字符串,只需获取返回节点的nodeName
属性。 这也适用于零长度选择(即只是一个插入位置)。
function getSelectionStart() {
var node = document.getSelection().anchorNode;
return (node.nodeType == 3 ? node.parentNode : node);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.