0

我想在页面中显示鼠标坐标,当我不声明 DOCTYPE 时它可以工作,但是当我声明 DOCTYPE 时它不会!你能帮我解决这个问题吗?这是我的代码:

<html>
<head>
    <title>problem</title>
</head>
<body>
    text...
<div id="show"></div>
<script>
    document.body.onmousemove = function(event) {
        document.body.innerHTML = "X: " + window.event.clientX + "<br />" + "Y: " + window.event.clientY;
    }
</script>
</body>
</html>

在上面的代码中,我可以毫无问题地获得 y 坐标,但是当我添加 doctype 时,它​​没有正确显示 y 坐标:

<DOCTYPE html>
<html>
<head>
    <title>problem</title>
</head>
<body>
    text...
<div id="show"></div>
<script>
    document.body.onmousemove = function(event) {
        document.body.innerHTML = "X: " + window.event.clientX + "<br />" + "Y: " + window.event.clientY;
    }
</script>
</body>
</html>

编辑

这是我的代码,现在可以完美运行。谢谢你们:

<!DOCTYPE html>
<html>
  <head>
    <title>problem</title>
  </head>
  <body>
    text...
    <div id="show"></div>
    <script>
    if (document.addEventListener) {
      document.addEventListener('mousemove', function(event) {
        document.body.innerHTML = "X: " + window.event.clientX + "<br />" + "Y: " + window.event.clientY;
      });
    } else {
      document.attachEvent("onmousemove", function(event) {
        document.body.innerHTML = "X: " + window.event.clientX + "<br />" + "Y: " + window.event.clientY;
      });

}
   </script>
  </body>
</html>
4

2 回答 2

0

DOCTYPE首先通过写作<!DOCTYPE html>而不是更正声明<DOCTYPE html>

其次,将您的脚本更改为:

document.addEventListener('mousemove', function(event) {
    document.body.innerHTML = "X: " + event.clientX + "<br />" + "Y: " + event.clientY;
});

对于在函数中传递的参数可以直接引用,写作window.eventevent将是对象的子window对象,也就是全局对象。

于 2015-08-24T07:34:26.227 回答
0

尝试使用事件监听器监听鼠标事件,如下所示:

<!DOCTYPE html>
<html>
  <head>
    <title>problem</title>
  </head>
  <body>
    text...
    <div id="show"></div>
    <script>
    document.addEventListener('mousemove', function(event) {
        document.body.innerHTML = "X: " + window.event.clientX + "<br />" + "Y: " + window.event.clientY;
    });
   </script>
  </body>
</html>
于 2015-08-24T07:13:58.093 回答