问题
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)
回答1:
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):
<head>
<title>Some "this" tests</title>
<script type="text/javascript">
var whatIs = (function(global) {
return function(that) {
// If String(that) isn't useful, try some stuff
if (String(that) == '[object]') {
if (that == global || that == window) {
alert('window');
} else if (typeof that.tagName == 'string') {
alert(that.tagName);
} else {
alert(that);
}
// Otherwise show that
} else {
alert(that);
}
}
})(this);
</script>
</head>
<body onclick="whatIs(this);" onload="whatIs(this);">
<div onmousedown="whatIs(this)">this</div>
</body>
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.
回答2:
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.
回答3:
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:
$('body').bind('click mousedown', function() {
alert(123);
});
回答4:
Try using the global window object instead:
<!DOCTYPE html>
<html><head></head><body onload="
window.addEventListener('click',function(e){
alert(123);
},false);
"></body></html>
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.
<!DOCTYPE html>
<html><head></head><body style="height:1000px; width:1000px" onload="
document.body.addEventListener('mousedown',function(e){
alert(123);
},false);
"></body></html>
来源:https://stackoverflow.com/questions/6246430/attaching-listeners-to-body-doesnt-work