gpt4 book ai didi

javascript - 了解 window.event 属性及其用法

转载 作者:可可西里 更新时间:2023-11-01 02:52:32 27 4
gpt4 key购买 nike

我不明白 window.event 或 window.event.srcElement 背后的动机。在什么情况下应该使用它?它在 DOM 中究竟代表什么?

最佳答案

这是什么w3school says关于事件对象:

Events are actions that can be detected by JavaScript, and the event object gives information about the event that has occurred.

Sometimes we want to execute a JavaScript when an event occurs, such as when a user clicks a button.

您可以使用以下方式处理事件:

node.onclick = function(e) {
// here you can handle event. e is an object.
// It has some usefull properties like target. e.target refers to node
}

但是 Internet Explorer 不会将事件传递给处理程序。相反,您可以使用在事件触发后立即更新的 window.event 对象。所以处理事件的跨浏览器方式:

node.onclick = function(e) {
e = e || window.event;
// also there is no e.target property in IE.
// instead IE uses window.event.srcElement
var target = e.target || e.srcElement;
// Now target refers to node. And you can, for example, modify node:
target.style.backgroundColor = '#f00';
}

关于javascript - 了解 window.event 属性及其用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6926963/

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