Javascript 鼠标坐标和声明 DOCTYPE

Javascript mouse coordinates and declaring DOCTYPE

我想在页面中显示鼠标坐标,当我不声明 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 坐标,但是当我添加文档类型时,它没有正确显示 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>

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

<!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>

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

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

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

因为函数传入的参数可以直接引用,写成window.event就是当eventwindow对象的子对象,也就是全局对象。