做小方块效果 要求:1.小方块活动范围在边框里 2.小方块靠近边框可以吸上去
时间: 2024-03-17 13:40:40 浏览: 22
这是一个基本的小方块效果,满足您的要求。您可以将其复制并粘贴到一个 HTML 文件中进行测试。
```html
<!DOCTYPE html>
<html>
<head>
<title>小方块效果</title>
<style>
.container {
width: 500px;
height: 500px;
border: 2px solid gray;
position: relative;
overflow: hidden; /* 确保小方块不会溢出 */
}
.box {
width: 50px;
height: 50px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* 将小方块居中 */
cursor: move; /* 光标变成移动样式 */
}
</style>
</head>
<body>
<div class="container">
<div class="box"></div>
</div>
<script>
var container = document.querySelector(".container");
var box = document.querySelector(".box");
var containerRect = container.getBoundingClientRect(); /* 获取容器位置 */
var boxRect = box.getBoundingClientRect(); /* 获取小方块位置 */
/* 给小方块添加拖动事件 */
box.addEventListener("mousedown", function(event) {
event.preventDefault(); /* 防止默认行为 */
document.addEventListener("mousemove", onMouseMove);
document.addEventListener("mouseup", onMouseUp);
});
/* 当鼠标移动时,更新小方块位置 */
function onMouseMove(event) {
var x = event.clientX - containerRect.left;
var y = event.clientY - containerRect.top;
/* 确保小方块在容器内 */
if (x < boxRect.width / 2) {
x = boxRect.width / 2;
}
if (x > containerRect.width - boxRect.width / 2) {
x = containerRect.width - boxRect.width / 2;
}
if (y < boxRect.height / 2) {
y = boxRect.height / 2;
}
if (y > containerRect.height - boxRect.height / 2) {
y = containerRect.height - boxRect.height / 2;
}
box.style.left = x + "px";
box.style.top = y + "px";
/* 如果小方块靠近边框,就吸附到边框上 */
if (x < boxRect.width) {
box.style.left = 0;
}
if (x > containerRect.width - boxRect.width * 1.5) {
box.style.left = containerRect.width - boxRect.width + "px";
}
if (y < boxRect.height) {
box.style.top = 0;
}
if (y > containerRect.height - boxRect.height * 1.5) {
box.style.top = containerRect.height - boxRect.height + "px";
}
}
/* 当鼠标松开时,停止拖动 */
function onMouseUp(event) {
document.removeEventListener("mousemove", onMouseMove);
document.removeEventListener("mouseup", onMouseUp);
}
</script>
</body>
</html>
```
在此示例中,我们创建了一个包含一个小方块的容器。我们使用 CSS 样式定义了容器和小方块的外观和位置,并使用 JavaScript 代码添加了拖动事件。
在拖动事件中,我们使用 event.clientX 和 event.clientY 属性来获取鼠标位置,并使用 container.getBoundingClientRect() 和 box.getBoundingClientRect() 方法来获取容器和小方块的位置。我们使用一些条件语句来确保小方块不会超出容器边界,并使用一些计算来将小方块居中。
最后,我们使用一些条件语句来检测小方块是否靠近边框,并将其吸附到边框上。如果小方块在容器的左边或上边,我们将其位置设置为 0。如果小方块在容器的右边或下边,我们将其位置设置为容器的宽度或高度减去小方块的宽度或高度。