文档类型和点击事件

doctype and onclick event

本文关键字:事件 类型 文档      更新时间:2023-09-26

有人可以解释为什么以下代码,我只是将div移动到鼠标单击位置,只有在我删除DOCTYPE标签时才有效?

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Prova</title>
    <style>
      .bbox{
        width: 10px;
        height:10px;
        position:absolute;
        background-color: orange;
    }
</style>
</head>
<body onclick = "moves()">
   <script>
       function moves(){
       var cordx;
       var cordy;
       var d;
       var e = window.event;
       d= document.getElementById('box');
       cordx = e.clientX;
       cordy = e.clientY;
       d.style.left = cordx;
      d.style.top = cordy;
    }
  </script>

<div class="bbox" id='box'></div>
</body>
</html>

CSS要求长度(0除外)有单位。

您正在将整数分配给 d.style.leftd.style.top

如果您忘记了 Doctype,那么浏览器会假设该页面是在 90 年代编写的,并模拟了那个时代的浏览器的错误。一旦这样的错误将CSS中的整数视为像素值而不是错误。

使用 + "px"