我发现自己处于一种情况,我想获取触发 selectionChange dom 事件的目标元素。
但根据 https://developer.mozilla.org/en-US/docs/Web/Events/selectionchange 判断,在正常(非输入,非文本区域)情况下,似乎 e.target 中的元素始终是文档对象。
那么这是否意味着我必须手动调用 window.getSelection,找出当前光标位置并以此方式找到 dom 节点?
有人知道捷径吗?或者一些工作示例会很好。
最佳答案
如果您的元素可以成为事件元素,请使用 document.activeElement
获取我们在其中选择的元素。这将适用于文本区域、输入以及设置了 tabindex
的元素。
// NOTE: activeElement can only be found on selectable elements!
document.addEventListener('selectionchange',function(){
document.getElementById('currentTag').innerHTML = document.activeElement.tagName;
});
#currentTag{
font-weight:bold;
}
<textarea>This is sample text you can replace and move your cursor within. Whee!</textarea>
<br><input type="text" placeholder="Input">
<p tabindex="0">P tag text is the best tag text. <span color="blue">Unless you have a span.</span></p>
<ol tabindex="0">
<li tabindex="0">Item 1</li>
<li tabindex="0">Item 2</li>
</ol>
<p id="currentTag"></p>
关于javascript - 如何获取 'selectionchange' dom 事件的目标元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40034875/