我尝试使用以下代码来拦截 mousedown
事件,然后重新分派(dispatch)它以便在任何元素获得焦点时都处于控制之下。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
document.addEventListener('mousedown', function (e) {
console.log('mousedown', e);
if (e.target.getAttribute('id') === 'target' && !e.__redispatched) {
console.log('cancelling');
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
setTimeout(function () {
var re = new MouseEvent('mousedown', {
bubbles: true,
cancelable: true,
view: window,
screenX: e.screenX,
screenY: e.screenY,
clientX: e.clientX,
clientY: e.clientY,
ctrlKey: e.ctrlKey,
shiftKey: e.shiftKey,
altKey: e.altKey,
button: e.button,
buttons: e.buttons,
relatedTarget: e.relatedTarget,
region: e.region
});
re.__redispatched = true;
document.getElementById('target').dispatchEvent(re);
}, 100);
}
})
</script>
<input id="target" type="text"/>
</body>
</html>
控制台显示事件已正确重新调度,因为它被 target
元素捕获,但焦点未获得该元素。
当我在不干预事件的情况下尝试这样做时,在处理 mousedown
事件之前就获得了焦点。
是否可以仅通过重新调度 mousedown
事件来处理此行为,还是我必须手动处理 focus
?
还是我对事件做错了什么?
最佳答案
focus
在接收到 mousedown
事件后被触发。但是,浏览器不会为 untrusted events 运行默认处理程序例如使用 dispatchEvent
触发的 MouseEvent
。
您必须手动聚焦
输入。
关于javascript - 将 mousedown 事件分派(dispatch)给元素不会使其获得焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35513857/