将侦听器附加到主体不起作用?
我不明白为什么这段代码不起作用:
<!DOCTYPE html>
<html><head></head><body onload="
document.body.addEventListener('mousedown',function(e){
alert(123);
},false);
"></body></html>
甚至没有任何错误......它什么也没做。
令人惊讶的是,如果我将 'mousedown'
更改为 'keydown'
它就可以工作
<!DOCTYPE html>
<html><head></head><body onload="
document.body.addEventListener('keydown',function(e){
alert(123);
},false);
"></body></html>
(顺便说一句,我正在使用 Chrome)
I can't figure out why this piece of code isn't working:
<!DOCTYPE html>
<html><head></head><body onload="
document.body.addEventListener('mousedown',function(e){
alert(123);
},false);
"></body></html>
There isn't even any error whatsoever.. it just does nothing.
amazingly if I change 'mousedown'
to 'keydown'
it works
<!DOCTYPE html>
<html><head></head><body onload="
document.body.addEventListener('keydown',function(e){
alert(123);
},false);
"></body></html>
(I'm using Chrome btw)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
工作正常 (查看代码)。
请注意,我添加了一些内容并向
body
添加了边框,以便您可以看到其尺寸。 如果删除内容,您看到的所有内容都是黑线。如果没有内容(像任何其他块元素一样),则body
不会占用任何空间,这意味着您无法在其中单击。您似乎认为
body
会遍布整个浏览器窗口,但事实并非如此。如果您将处理程序附加到
window
,它会获取可见区域内发生的所有事件。It works fine (see the code).
Notice that I added some content and added a border to
body
so that you can see its dimensions. If you remove the content, everything you see is a black line.body
does not take up any space if there is no content (like any other block element) which implies you cannot click inside of it.It seems you thought that
body
would spread across the whole browser window, but that is not the case.If you attach the handler to
window
instead, it gets all events that happen inside the visible area.附加到 body 元素的侦听器中的 this 值在不同浏览器中的行为略有不同。在 Firefox 和旧版本的 IE 中尝试以下操作(请注意,它是专门针对这种情况的,它并不意味着是一般的“这是什么?”功能):
在所有浏览器中,onload 显示 window< /em> 并单击 div 将 this 显示为 div。单击正文将在 Firefox 中显示 this 为 window,但在 IE、Opera 和 Chrome 中显示为 body 元素。
The value of this in listeners attached to the body element behaves a little differently in different browsers. Try the following in Firefox and an older version of IE (note that it's specifically for this case, it isn't meant to be a general "what is this?" function):
In all browsers, the onload shows window and clicking on the div show this as the div. Clicking on the body shows this to be window in Firefox but the body element in IE, Opera and Chrome.
另一种方法是使用 jQuery 绑定。它不仅可以减少您的代码量,而且还受到大多数浏览器的支持。试试这个:
An alternative is to use jQuery bind. It does not only make you code less but is also supported by most browsers. Try this one:
尝试使用全局窗口对象:
对于给定的 HTML,主体没有高度和宽度,因此当您单击窗口时它不会接收任何鼠标事件。但它仍然可以接收关键事件。如果你给它一个高度和宽度,它就会起作用。
Try using the global window object instead:
For the given HTML, the body has no height and width, so it will not receive any mouse events when you click on the window. It still can receive key events though. If you give it a height and width, it will work.