Loading

JS实现元素拖拽功能

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <style type="text/css">
      li {
        position: absolute;
        left: 0;
        width: 100%;
        list-style: none;
        line-height: 40px;
        cursor: pointer;
        border-bottom: 1px solid blue;
        background-color: rgba(16, 87, 243, 0.3);
        text-align: center;
      }
    </style>
  </head>
  <body>
    <ul id="box"></ul>
    <script type="text/javascript">
      const box = document.querySelector('#box')
      box.style.position = 'relative'
      let lis = ['TEXT1', 'TEXT2', 'TEXT3', 'TEXT4', 'TEXT5', 'TEXT6'];
      lis.forEach((v, i) => {
        const li = document.createElement('li')
        li.innerText = "ITEM" + (i + 1);
        li.style.top = (i + 1) * 40 + 'px';
        move(li)
        box.appendChild(li)
      })

      function move(element) {
        element.onmousedown = function(event) {
          const diffX = event.clientX - element.offsetLeft;
          const diffY = event.clientY - element.offsetTop;
          document.onmousemove = function(event) {
            const moveX = event.clientX - diffX;
            const moveY = event.clientY - diffY;
            element.style.left = moveX + 'px';
            element.style.top = moveY + 'px';
          }
        }
        document.onmouseup = function() {
          document.onmousemove = null;
        }
      }
    </script>
  </body>
</html>
posted @ 2020-07-08 15:35  fsdffsdf  阅读(534)  评论(0编辑  收藏  举报