实现div拖拽demo

实现div拖拽demo_第1张图片

示例代码:

DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Documenttitle>
    <style>
      html {
        height: 100%;
      }
      body {
        height: 100%;
        margin: 0;
        position: relative;
      }
      .drag {
        position: absolute;
        top: 0;
        left: 0;
        width: 100px;
        height: 100px;
        background-color: red;
        cursor: move;
      }
    style>
  head>
  <body>
    <div class="drag">div>
    <script>
      let drag = document.querySelector('.drag');
      let divX = 0;
      let divY = 0;
      let documentMousemove = (e) => {
        drag.style.left = e.clientX - divX + 'px';
        drag.style.top = e.clientY - divY + 'px';
        // 禁止元素被拖出屏幕
        if (drag.offsetLeft < 0) {
          drag.style.left = 0;
        }
        if (drag.offsetTop < 0) {
          drag.style.top = 0;
        }
        let winW = window.innerWidth;
        if (e.clientX - divX > winW - drag.offsetWidth) {
          // 屏幕可视区域宽度 - 元素宽度 得到元素可移动的最大横向距离
          drag.style.left = winW - drag.offsetWidth + 'px';
        }
        let winH = window.innerHeight;
        if (e.clientY - divY > winH - drag.offsetHeight) {
          // 同理
          drag.style.top = winH - drag.offsetHeight + 'px';
        }
      };
      let dragMousedown = (e) => {
        // 拖拽点距离拖拽元素左上角的距离
        divX = e.clientX - drag.offsetLeft;
        divY = e.clientY - drag.offsetTop;
        document.addEventListener('mousemove', documentMousemove);
      };
      let documentMouseup = (e) => {
        document.removeEventListener('mousemove', documentMousemove);
      };
      drag.addEventListener('mousedown', dragMousedown);
      document.addEventListener('mouseup', documentMouseup);
    script>
  body>
html>

你可能感兴趣的:(前端,javascript,html)