js实现元素拖动

2021-04-16  本文已影响0人  Gambler_194b
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>js实现元素拖动</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      #drag {
        position: fixed;
        width: 100px;
        height: 100px;
        background-color: #009988;        
      }
    </style>
  </head>

  <body>
    <div id="drag"></div>
    <script>
      var div = document.getElementById("drag");
      div.onmousedown = function(e) {
        e = e || window.event;
        var x = e.offsetX;
        var y = e.offsetY;
        //鼠标移动时
        document.onmousemove = function(e) {
          e = e || window.event;
          div.style.left = e.clientX - x + "px";
          div.style.top = e.clientY - y + "px";
        };
      };
      //松开手时
      div.onmouseup = function() {
        document.onmousemove = null;
      };
    </script>
  </body>
</html>

上一篇 下一篇

猜你喜欢

热点阅读