我们将监听器绑定(bind)到 contenteditable
节点 - 为什么 event.target
在按键(向上、按下或向下)事件上传递错误的父级,但在点击事件何时?
HTML:
<div class="wysiwyg_editor" contenteditable="true">
<h2>Hello There</h2>
<p>If you click on LI, nodeName will be 'LI', but if you use keys to move around, nodeName will be 'DIV', strange!</p>
<p><b>Why :() ?</b></p>
<ul>
<li>Heros are forever</li>
<li><b>Wars</b> are weapons of dirty <b>politicians</b></li>
</ul>
</div>
JS:
let div = document.querySelector(".wysiwyg_editor");
let f = function(event) {
console.log(`Event Type: ${event.type} Target: ${event.target.nodeName}`);
}
div.addEventListener('click',f);
div.addEventListener('keyup',f);
我做错了什么?
(这里是jquery version(问题更新之前))
要在 codepen 中重现问题,请单击一些文本并对其进行编辑 - 然后在控制台上查看单击和键盘事件。
最佳答案
按键的定位似乎仅适用于输入标签和具有 contenteditable 属性的标签。由于您的 contenteditable 仅位于包装 div 上,因此目标将始终引用它。在子项中键入内容将冒泡到可内容编辑的父项。为了获得您正在寻找的结果,我将 contenteditable 放在了子项上:
$('.wysiwyg_editor').bind('click keyup',
function(event) {
console.log(`Event Type: ${event.type} Target: ${event.target.nodeName}`);
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wysiwyg_editor">
<h2>Hello There</h2>
<p class="wysiwyg_editor" contenteditable="true">If you click on LI, nodeName will be 'LI', but if you use keys to move around, nodeName will be 'DIV', strange!</p>
<p><b>Why :() ?</b></p>
<ul>
<li class="wysiwyg_editor" contenteditable="true">Heros are forever</li>
<li class="wysiwyg_editor" contenteditable="true"><b>Wars</b> are weapons of dirty <b>politicians</b></li>
</ul>
</div>
关于javascript - Event.target 在关键事件上并不精确,但在点击事件上却完美,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53072430/