将听众附加到身体不起作用? [英] attaching listeners to body doesn't work?

查看:212
本文介绍了将听众附加到身体不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么这段代码不起作用:

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.

令人惊讶的是,如果我将'mousedown'更改为'keydown' p>

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>

(我正在使用chrome btw)

(I'm using chrome btw)

推荐答案

附加到body元素的监听器中的 的值在不同的浏览器中有所不同。在Firefox和旧版本的IE中尝试以下操作(请注意,这是特定的,这不是一般的这是什么功能):

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>

在所有浏览器中,onload显示窗口并点击div显示这个作为div。单击主体将在Firefox中显示 窗口,但IE,Opera和Chrome中的主体元素。

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.

这篇关于将听众附加到身体不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆