**在JavaScript中实现图片拖拽排序可以通过以下步骤完成。在这个例子中,我将使用HTML、CSS和JavaScript来实现一个简单的图片拖拽排序的效果。
HTML结构:**

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Drag and Drop Image Sorting</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>

  <div id="image-container" class="image-container">
    <div class="draggable" draggable="true"><img src="image1.jpg" alt="Image 1"></div>
    <div class="draggable" draggable="true"><img src="image2.jpg" alt="Image 2"></div>
    <div class="draggable" draggable="true"><img src="image3.jpg" alt="Image 3"></div>
    <!-- Add more images as needed -->
  </div>

  <script src="script.js"></script>
</body>
</html>

CSS样式 (styles.css):

body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;
}

.image-container {
  display: flex;
}

.draggable {
  border: 1px solid #ccc;
  margin: 5px;
  cursor: grab;
}

.dragging {
  opacity: 0.5;
  cursor: grabbing;
}

JavaScript代码 (script.js):

const imageContainer = document.getElementById('image-container');
let draggedElement = null;

// 添加拖拽事件监听器
imageContainer.addEventListener('dragstart', (event) => {
  draggedElement = event.target.closest('.draggable');
  draggedElement.classList.add('dragging');
});

imageContainer.addEventListener('dragend', () => {
  if (draggedElement) {
    draggedElement.classList.remove('dragging');
    draggedElement = null;
  }
});

imageContainer.addEventListener('dragover', (event) => {
  event.preventDefault();
  const afterElement = getDragAfterElement(imageContainer, event.clientY);
  const draggable = document.querySelector('.dragging');

  if (afterElement == null) {
    imageContainer.appendChild(draggable);
  } else {
    imageContainer.insertBefore(draggable, afterElement);
  }
});

// 获取拖拽位置
function getDragAfterElement(container, y) {
  const draggableElements = [...container.querySelectorAll('.draggable:not(.dragging)')];

  return draggableElements.reduce((closest, child) => {
    const box = child.getBoundingClientRect();
    const offset = y - box.top - box.height / 2;

    if (offset < 0 && offset > closest.offset) {
      return { offset, element: child };
    } else {
      return closest;
    }
  }, { offset: Number.NEGATIVE_INFINITY }).element;
}

这个例子中,每个图片都包裹在一个可拖拽的

元素中,通过设置draggable="true"属性来启用拖拽功能。JavaScript代码监听拖拽相关的事件,并在拖拽过程中更新图片的位置。CSS用于样式化拖拽时的效果。这是一个简单的例子,你可以根据自己的需求进行扩展。

版权属于:泽泽社长
本文链接:https://blog.zezeshe.com/archives/3031.html
本站未注明转载的文章均为原创,并采用 CC BY-NC-SA 4.0 授权协议,转载请注明来源,谢谢!