我想获取写入游标时所在的节点
document.getElementById('parent').addEventListener('keypress', function(e) {
console.log(e.target);
});
.root {
padding-right: 1px;
}
#parent>div {
border-color: yellow;
float: left;
}
<div id="parent" contenteditable=true style="border: black 2px solid; height:200px">
<div class="root" id="1">Qué</div>
<div class="root" id="2">es</div>
<div class="root" id="3">Lorem</div>
<div class="root" id="4">Ipsum</div>
</div>
问题很复杂,因为我为每个单词使用了一个div。
我需要使用div,以便您可以在文字中显示建议(我正在执行拼写检查)
最佳答案
您可以使用window.getSelection()
获取光标下的实际节点:
document.getElementById('parent').addEventListener('keydown', event => {
const actualTarget = window.getSelection().anchorNode.parentNode;
console.log(actualTarget);
});
.root {
padding-right: 1px;
}
#parent>div {
border-color: yellow;
float: left;
}
<div id="parent" contenteditable="true" style="border: black 2px solid; height:200px">
<div class="root" id="1">Qué</div>
<div class="root" id="2">es</div>
<div class="root" id="3">Lorem</div>
<div class="root" id="4">Ipsum</div>
</div>
关于javascript - 获取您编写的节点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51111395/