拖拽列表简单实现

发布时间:2023年12月22日

样式部分:

<style>
      .item {
        width: 500px;
        text-align: center;
        margin-bottom: 5px;
        height: 40px;
        line-height: 40px;
        border-radius: 5px;
        color: #fff;
        margin: 5 auto;
        background-color: red;
      }
      .item.moving {
        background: transparent;
        color: transparent;
        border: 1px dashed #ccc;
      }
      
    </style>
<div class="container">
      <div id="apple" draggable="true" class="item">苹果</div>
      <div id="banana" draggable="true" class="item">香蕉</div>
      <div id="ss" draggable="true" class="item">黄梨</div>
      <div id="sdf" draggable="true" class="item">西瓜</div>
      <div id="5sdf" draggable="true" class="item">葡萄</div>
      <div id="dfdf" draggable="true" class="item">留恋</div>
    </div>

<script>
    const con = document.querySelector('.container');
    let selfNode;
    con.ondragstart = e => {
      e.dataTransfer.effectAllowed = 'move';
      e.dataTransfer.setData('Text', e.target.id);

      console.log(e);
      setTimeout(() => {
        e.target.classList.add('moving');
      }, 0);
      selfNode = e.target;
    };
    con.ondragover = e => {
      e.preventDefault();
    };
    con.ondragenter = e => {
      e.preventDefault();
      console.log('enter', e);
      if (e.target === con || e.target === selfNode) {
        return;
      }
      const children = Array.from(con.children);
      const selfIndex = children.indexOf(selfNode);
      const targetIndex = children.indexOf(e.target);
      console.log(selfNode, e.target);
      if (selfIndex < targetIndex) {
        con.insertBefore(selfNode, e.target.nextElementSibling);
      } else {
        con.insertBefore(selfNode, e.target);
      }
    };
    con.ondragend = e => {
      selfNode.classList.remove('moving');
    };
  </script>

文章来源:https://blog.csdn.net/m0_53273062/article/details/135145837
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。