有没有办法确定 JS 事件是以编程方式还是通过实际交互触发的

Is there a way to determine if a JS event was fired programmatically or by an actual interaction?

本文关键字:交互 编程 JS 有没有 事件 方式      更新时间:2023-09-26

假设我以编程方式将焦点设置在具有简单document.getElementById('myTextArea').focus();textarea上。在那textarea我有一个onFocus事件:

document.getElementsByName('myTextArea')[0].onFocus = function () {
    alert('I’m focused!');
};

我只希望在用户实际关注textarea而不是在我以编程方式设置焦点时触发该onFocus

onFocus有没有办法判断事件是由代码还是由人类触发的,而无需传入我自己的参数?

是的,当浏览器触发时,它会产生一个"原始事件"。