帮我用js写一个九宫格拖拽
时间: 2023-05-19 17:07:01 浏览: 60
当然可以,以下是一个简单的九宫格拖拽的实现代码:
HTML:
```
<div id="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
```
CSS:
```
#container {
width: 300px;
height: 300px;
border: 1px solid #000;
display: flex;
flex-wrap: wrap;
}
.box {
width: 100px;
height: 100px;
background-color: #ccc;
border: 1px solid #000;
box-sizing: border-box;
cursor: move;
}
```
JavaScript:
```
var container = document.getElementById('container');
var boxes = document.getElementsByClassName('box');
var activeBox = null;
var activeBoxIndex = null;
var startX = null;
var startY = null;
for (var i = 0; i < boxes.length; i++) {
boxes[i].addEventListener('mousedown', function(e) {
activeBox = e.target;
activeBoxIndex = Array.prototype.indexOf.call(boxes, activeBox);
startX = e.clientX;
startY = e.clientY;
});
boxes[i].addEventListener('mousemove', function(e) {
if (activeBox) {
var deltaX = e.clientX - startX;
var deltaY = e.clientY - startY;
activeBox.style.transform = 'translate(' + deltaX + 'px, ' + deltaY + 'px)';
}
});
boxes[i].addEventListener('mouseup', function(e) {
if (activeBox) {
var endX = e.clientX;
var endY = e.clientY;
var endBoxIndex = Math.floor(endY / 100) * 3 + Math.floor(endX / 100);
if (endBoxIndex !== activeBoxIndex) {
var endBox = boxes[endBoxIndex];
container.insertBefore(activeBox, endBox);
}
activeBox.style.transform = 'translate(0, 0)';
activeBox = null;
activeBoxIndex = null;
}
});
}
```
这段代码实现了一个简单的九宫格拖拽效果,你可以在 HTML 中添加更多的 box 元素来增加九宫格的数量。