原生javascript实现拖拽

深海里的星星i / 2023-09-05 / 原文

<!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>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    .container {
      width: 100%;
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 10px;
    }

    .container .item {
      height: 100px;
    }
  </style>
</head>

<body>
  <div class="container">
  </div>

  <script>
    // 生成随机颜色    
    const color = () => {
      const rd = () => parseInt(Math.random() * 256)
      return `rgb(${rd()},${rd()},${rd()})`
    }

    // 获取对象
    // 互换对象
    let fromId = ''
    let toId = ''

    const list = Array.from({ length: 7 }, (_, i) => {
      return {
        id: i + 1,
        content: `${i}${i}${i}${i}`,
        color: color()
      }
    })

    const container = document.querySelector('.container')
    function render() {
      container.innerHTML = ''
      list.map(i => {
        const div = document.createElement('div')
        div.setAttribute('draggable', true)
        div.setAttribute('data-id', i.id)
        div.setAttribute('class', 'item')
        div.setAttribute('style', `background-color: ${i.color}`)
        div.innerText = i.content
        container.appendChild(div)
      })
      bindEvent()
    }
    render()




    function bindEvent() {
      const items = document.querySelectorAll('.item')
      items.forEach(i => {

        i.addEventListener('dragenter', (ev) => {
          toId = ev.target.getAttribute('data-id') / 1
        })



        i.addEventListener('dragend', (ev) => {
          fromId = ev.target.getAttribute('data-id') / 1

          const fromIndex = list.findIndex(i => i.id === fromId)
          const fromObj = { ...list[fromIndex] }

          const toIndex = list.findIndex(i => i.id === toId)
          const toObj = { ...list[toIndex] }

          list[fromIndex] = { ...toObj }
          list[toIndex] = { ...fromObj }
          render()
        })

      })
    }
  </script>
</body>

</html>

拖动一次可以让两个元素互换位置

比如拖动让 4444 和 6666 换了个位置