将 mousedown 事件分派给元素不会使其获得焦点

Dispatching mousedown event to element won't give it focus

我尝试使用以下代码来拦截 mousedown 事件,然后重新调度它,以便在任何元素获得焦点时都能得到控制。

<!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? 还是我对活动做错了什么?

接收到mousedown事件后触发focus。但是,浏览器不会 运行 untrusted events 的默认处理程序,例如使用 dispatchEvent.

触发的 MouseEvent

您必须focus手动输入。