我尝试在“contentEditable-Div”中获取插入符处的所有 Node 。总是在 Key-Down 之后列出所有 Node 。
<div id="MyDiv" contentEditable="true">
<h1>header</h1>
<p>this is a test </p>
<a href="http://www...">Href-Test</a>
<ol>
<li>Google Chrome</li>
<li>Internet Explorer</li>
<li>Mozilla Firefox</li>
<li>Safari</li>
<li>Opera</li>
</ol>
<p> 123
<ol>
<li><strong> 1 2 3 </strong> Test </li>
<li><h4>This-is-a-pointer</h4></li>
</ol>
</p>
<br />
<ul> <li> Test "<em>Test</em> <b>Test</b>" </li></ul>
jQuery 中的 Key-Down 函数:
$("#MyDiv").keydown(function(event) {
alert('1. '+ event.target.nodeName );
alert('2. '+ ' ? ' );
alert('3. '+ ' ? ' ); });
如果插入符号是“Google Chrome”,那么我希望得到如下结果: div -> ol -> li 或者如果插入符号是“This-is-a-pointer”,那么我希望得到如下结果: div -> P -> ol -> li -> h4
我试过如下:
alert('1->'+ event.target.nodeName ); // --> DIV
alert('2->'+ $(target.children()).prop('tagName') ); // --> P
alert('3->'+ $(target.children().children()).prop('tagName') ); // --> I
但这并没有提供预期的解决方案。 任何想法? 提前致谢。
最佳答案
它无法正常工作,因为 $(event.target).children().prop("tagName")
返回 id="MyDiv"
中第一个 child 的 tagName .
您可以尝试使用 document.elementFromPoint(x, y)
方法来搜索 DOM 元素。
x
和 y
- 鼠标坐标。您可以像 this 中描述的那样获取它们发布。
可以看到样本here .
希望对您有所帮助。
关于javascript - 获取 "contentEditable-Div"中插入符处的所有 Node ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26235393/