在 contenteditable 中找到光标定位的元素 id
Find the cursor targeted element id in contenteditable
在 contenteditable div 中,我有不同的子元素 ID。 光标移动时在contenteditable标签内。我需要获取光标位置元素 ID。
像这样:示例
- if
cursor
position on one
string 得到输出是光标位置元素的id
1
- 如果是
two
输出2
我这样尝试,但找不到光标目标子 ID。它仅在父级上。
function check(e){
console.log($(e.target).attr('id'))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contentEditable="true" id="res" tabindex="2" onkeydown="check(event)">solve:
<span id="1">one</span>
<p id="2">two</p>
<i id="3">three</i>
</div>
你可以这样做:
$('#res').on('keyup', function() {
var el = window.getSelection().getRangeAt(0).commonAncestorContainer.parentNode;
console.log(el.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contentEditable="true" id="res" tabindex="2">solve:
<span id="1" class='number'>one</span>
<p id="2" class='number'>two</p>
<i id="3" class='number'>three</i>
</div>
您可以在 link 阅读有关 window.getSelection()
的内容。
您可以在 link.
阅读有关 window.getSelection()
与 getRangeAt()
结合使用的信息
在 contenteditable div 中,我有不同的子元素 ID。 光标移动时在contenteditable标签内。我需要获取光标位置元素 ID。
像这样:示例
- if
cursor
position onone
string 得到输出是光标位置元素的id1
- 如果是
two
输出2
我这样尝试,但找不到光标目标子 ID。它仅在父级上。
function check(e){
console.log($(e.target).attr('id'))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contentEditable="true" id="res" tabindex="2" onkeydown="check(event)">solve:
<span id="1">one</span>
<p id="2">two</p>
<i id="3">three</i>
</div>
你可以这样做:
$('#res').on('keyup', function() {
var el = window.getSelection().getRangeAt(0).commonAncestorContainer.parentNode;
console.log(el.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contentEditable="true" id="res" tabindex="2">solve:
<span id="1" class='number'>one</span>
<p id="2" class='number'>two</p>
<i id="3" class='number'>three</i>
</div>
您可以在 link 阅读有关 window.getSelection()
的内容。
您可以在 link.
阅读有关window.getSelection()
与 getRangeAt()
结合使用的信息