以下是一个示例代码,演示了当边框出现时移动的div:
HTML代码:
CSS代码:
.moveable-box {
width: 100px;
height: 100px;
background-color: red;
position: relative;
transition: left 0.5s ease, top 0.5s ease;
}
.moveable-box:hover {
border: 5px solid blue;
}
.moveable-box:hover::before {
content: "";
display: block;
width: 100%;
height: 100%;
border: 5px solid transparent;
position: absolute;
top: -5px;
left: -5px;
pointer-events: none;
}
JavaScript代码:
const box = document.getElementById("box");
const boxRect = box.getBoundingClientRect();
document.addEventListener("mousemove", (e) => {
const mouseX = e.clientX;
const mouseY = e.clientY;
if (mouseX >= boxRect.left && mouseX <= boxRect.right && mouseY >= boxRect.top && mouseY <= boxRect.bottom) {
const offsetX = mouseX - (boxRect.left + boxRect.width / 2);
const offsetY = mouseY - (boxRect.top + boxRect.height / 2);
box.style.left = `${boxRect.left + offsetX}px`;
box.style.top = `${boxRect.top + offsetY}px`;
}
});
以上代码中,我们首先给div添加了一个class为"moveable-box",在鼠标悬停时给div添加了一个蓝色的边框。通过CSS的:hover伪类和::before伪元素,我们实现了边框的出现和移动时的效果。
然后,我们使用JavaScript监听整个文档的mousemove事件,当鼠标移动时,判断鼠标的位置是否在div的边界内。如果在边界内,我们计算鼠标在div内部的偏移量,并基于当前div的位置进行移动,实现了div的移动效果。
请注意,以上代码只是一个基本示例,实际使用时可能需要根据具体需求进行适当的修改和优化。
上一篇:边框传输动画在整个过程中始终可见
下一篇:边框出现在图像内部而非图像周围