用JS拖拽画一个正方体
时间: 2023-06-20 07:04:42 浏览: 128
好的,下面是用JS拖拽画一个正方体的代码:
HTML部分:
```html
<div id="cube"></div>
```
CSS部分:
```css
#cube {
position: absolute;
width: 100px;
height: 100px;
background-color: blue;
transform-style: preserve-3d;
cursor: move;
}
```
JS部分:
```javascript
let cube = document.getElementById("cube");
let isDragging = false;
let currentX;
let currentY;
let initialX;
let initialY;
let xOffset = 0;
let yOffset = 0;
cube.addEventListener("mousedown", dragStart);
cube.addEventListener("mouseup", dragEnd);
cube.addEventListener("mousemove", drag);
function dragStart(e) {
initialX = e.clientX - xOffset;
initialY = e.clientY - yOffset;
if (e.target === cube) {
isDragging = true;
}
}
function dragEnd(e) {
initialX = currentX;
initialY = currentY;
isDragging = false;
}
function drag(e) {
if (isDragging) {
currentX = e.clientX - initialX;
currentY = e.clientY - initialY;
xOffset = currentX;
yOffset = currentY;
setTranslate(currentX, currentY, cube);
}
}
function setTranslate(xPos, yPos, el) {
el.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
}
```
通过以上代码,我们可以在页面上看到一个蓝色的正方体,鼠标按下后可以拖拽正方体移动。
阅读全文