gpt4 book ai didi

javascript - dispatchEvent 是否触发 `default` 处理程序?

转载 作者:行者123 更新时间:2023-12-03 12:34:00 25 4
gpt4 key购买 nike

我创建了这个简短的片段来测试是否可以触发 default JavaScript 事件中的处理程序。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script></script>
document.addEventListener('mousedown', function (e){
console.log('mousedown', e);
if (e.target === document.getElementById('target')) {
if (!e.__redispatched) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
var ne = new MouseEvent('mousedown', e);
ne.__redispatched = true;
setTimeout(function (){
e.target.focus();
e.target.dispatchEvent(ne);
}, 1000);
}
}
}, true);
</head>
<body>
<input type="text" id="target"/>
<input type="text"/>
</body>
</html>
我预计 target input 将接收事件并正常处理它,从而将插入符号移动到正确的位置(就像它通常在 mousedown 上所做的那样)。但什么也没有发生。
我的问题:
我在 dispatchEvent 上做错了吗?还是浏览器在处理合成事件时忽略默认处理程序?有什么 Material /证据吗?

最佳答案

不幸的是,浏览器确实忽略了 的默认事件处理程序。不受信任事件。

3.4 Trusted events in the W3C UI Events Specification

Events that are generated by the user agent, either as a result of user interaction, or as a direct result of changes to the DOM, are trusted by the user agent with privileges that are not afforded to events generated by script through the DocumentEvent.createEvent("Event") method, modified using the Event.initEvent() method, or dispatched via the EventTarget.dispatchEvent() method. The isTrusted attribute of trusted events has a value of true, while untrusted events have a isTrusted attribute value of false.

Most untrusted events should not trigger default actions, with the exception of the click event. This event always triggers the default action, even if the isTrusted attribute is false (this behavior is retained for backward-compatibility). All other untrusted events must behave as if the Event.preventDefault() method had been called on that event.

关于javascript - dispatchEvent 是否触发 `default` 处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35526092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com