javascript/所见即所得parentElement返回div而不是p元素
我正在尝试使用 contentEditable=true 使用 javascript 构建一个所见即所得编辑器。我遇到的问题是,在 IE 上 document.selection.createRange().parentElement() 返回 contenteditable 设置为 true 的元素。为了更容易理解,我给你举一个例子:
<div contenteditable="true">
<p>lorem ip|sum dolor</p>
</div>
在这个例子中' | ' 代表插入符号。在 chrome 中,当我使用 commonAncestorContainer 时,本例中返回的元素是 p,而在 IE 中,parentElement 返回容器 div。根据我的理解,浏览器会忽略这些元素,因此我无法弄清楚哪个元素是焦点。我不会问“是否有什么办法”,因为我已经看到了非常好的所见即所得编辑器,因此我的问题是如何在这个示例中获得“真正的”父元素? :)
顺便说一句,因为我是新用户,所以我无法创建标签。我相信“parentElement”对于这个问题来说是一个很好的标签。
I am trying to build a WYSIWYG editor with javascript using contentEditable=true. The point which I'm stucked is that on IE document.selection.createRange().parentElement() returns the element that contenteditable is set to true. For an easier comprehension I'll give you an example:
<div contenteditable="true">
<p>lorem ip|sum dolor</p>
</div>
In this example the ' | ' represents the caret. While in chrome when I use the commonAncestorContainer the returning element is p in this example, in IE parentElement returns the container div. In my understanding the browser is ignoring the elements and therefore I cannot figure out on what element is the focus. I won't ask "if there is any way" since I've seen pretty good working WYSIWYG editors, therefore my question is how can I get the "real" parent element in this example? :)
Ah btw, since I'm a new user I can't create tags. I believe "parentElement" would be a good tag for this question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
DOM
Range
的commonAncestorContainer
和TextRange
的parentElement()
略有不同:commonAncestorContainer
code> 返回包含整个范围的最深节点(可以是文本节点),而parentElement()
返回包含整个 TextRange 的最深元素。在您的示例中,commonAncestorContainer
将是文本节点“lorem ipsum dolor”,而parentElement()
将返回元素。如果这就是您想要的,您可以通过检查commonAncestorContainer的nodeType来使用Range获得它:
DOM
Range
'scommonAncestorContainer
andTextRange
'sparentElement()
are slightly different:commonAncestorContainer
returns the deepest node (which could be a text node) that contains the whole range whileparentElement()
returns the deepest element that contains the whole TextRange. In your example,commonAncestorContainer
would be the text node "lorem ipsum dolor" whileparentElement()
would return the<p>
element. If that's what you want, you can get that with Range by checkingcommonAncestorContainer
's nodeType: