写一个多个div任意位置拖拽功能
时间: 2023-07-13 15:41:06 浏览: 117
拖动多个div
5星 · 资源好评率100%
好的,以下是一个实现多个div任意位置拖拽的示例代码:
HTML部分:
```html
<div id="myDiv1" class="draggable">可拖动的div1</div>
<div id="myDiv2" class="draggable">可拖动的div2</div>
<div id="myDiv3" class="draggable">可拖动的div3</div>
```
CSS部分:
```css
.draggable {
position: absolute;
cursor: move;
}
```
JavaScript部分:
```javascript
var draggables = document.querySelectorAll(".draggable");
var activeDraggable = null;
var initialX, initialY, currentX, currentY, xOffset = 0, yOffset = 0;
draggables.forEach(function(draggable) {
draggable.addEventListener("mousedown", dragStart);
draggable.addEventListener("mouseup", dragEnd);
draggable.addEventListener("mousemove", drag);
});
function dragStart(event) {
activeDraggable = this;
initialX = event.clientX - xOffset;
initialY = event.clientY - yOffset;
}
function dragEnd(event) {
initialX = currentX;
initialY = currentY;
activeDraggable = null;
}
function drag(event) {
if (activeDraggable) {
event.preventDefault();
currentX = event.clientX - initialX;
currentY = event.clientY - initialY;
xOffset = currentX;
yOffset = currentY;
setTranslate(currentX, currentY, activeDraggable);
}
}
function setTranslate(xPos, yPos, el) {
el.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
}
```
这个代码会使得拥有class为draggable的所有div元素可以被拖动,并且当拖动结束时会被放置在最后一次拖动的位置上。可以通过修改CSS样式来控制这些div元素的样式和位置。
阅读全文