美文网首页
js实现元素拖动

js实现元素拖动

作者: Gambler_194b | 来源:发表于2021-04-16 15:10 被阅读0次
    <!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>
    
    

    相关文章

      网友评论

          本文标题:js实现元素拖动

          本文链接:https://www.haomeiwen.com/subject/eweelltx.html