补全下面的html和css代码,实现这个功能可以分为两个步骤: 实现小球的拖拽 可以通过监听小球的mousedown、mousemove和mouseup事件,实现小球的拖拽。具体实现方法如下: 复制 var ball = document.getElementById("ball"); var container = document.getElementById("container"); var isDragging = false; var offsetX = 0; var offsetY = 0; ball.addEventListener("mousedown", function(e) { isDragging = true; offsetX = e.offsetX; offsetY = e.offsetY; }); document.addEventListener("mousemove", function(e) { if (isDragging) { var x = e.clientX - offsetX; var y = e.clientY - offsetY; ball.style.left = x + "px"; ball.style.top = y + "px"; } }); document.addEventListener("mouseup", function() { isDragging = false; }); 判断小球是否移动到框里 可以通过判断小球是否与框的边界相交,来判断小球是否移动到框里。具体实现方法如下: 复制 var ballRect = ball.getBoundingClientRect(); var containerRect = container.getBoundingClientRect(); if ( ballRect.left >= containerRect.left && ballRect.right <= containerRect.right && ballRect.top >= containerRect.top && ballRect.bottom <= containerRect.bottom ) { // 小球在框里 } else { // 小球不在框里 } 把这两个步骤结合起来,就可以实现拖拽小球移动到框里的功能了。
时间: 2024-01-15 08:02:43 浏览: 122
前端canvas案例,可拖拽的小球。
HTML代码:
```html
<div id="container">
<div id="ball"></div>
</div>
```
CSS代码:
```css
#container {
width: 300px;
height: 300px;
border: 1px solid black;
position: relative;
}
#ball {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
cursor: move;
}
```
完整的JavaScript代码:
```javascript
var ball = document.getElementById("ball");
var container = document.getElementById("container");
var isDragging = false;
var offsetX = 0;
var offsetY = 0;
ball.addEventListener("mousedown", function(e) {
isDragging = true;
offsetX = e.offsetX;
offsetY = e.offsetY;
});
document.addEventListener("mousemove", function(e) {
if (isDragging) {
var x = e.clientX - offsetX;
var y = e.clientY - offsetY;
ball.style.left = x + "px";
ball.style.top = y + "px";
}
});
document.addEventListener("mouseup", function() {
isDragging = false;
var ballRect = ball.getBoundingClientRect();
var containerRect = container.getBoundingClientRect();
if (
ballRect.left >= containerRect.left &&
ballRect.right <= containerRect.right &&
ballRect.top >= containerRect.top &&
ballRect.bottom <= containerRect.bottom
) {
alert("小球在框里");
} else {
alert("小球不在框里");
}
});
```
注意:需要把JavaScript代码放在HTML代码的下面,或者等待DOM加载完毕后再执行。
阅读全文