JS 实现可移动 Div,碰到边缘反弹,鼠标悬停暂停
以下是一个实现该功能的代码示例:
HTML代码:
<div id='div1'>我是一个可移动的div</div>
CSS代码:
#div1 {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 0;
left: 0;
cursor: move;
z-index: 9999;
}
#div1 .close {
position: absolute;
top: 0;
right: 0;
cursor: pointer;
}
JavaScript代码:
var div1 = document.getElementById('div1');
var close = document.createElement('div');
close.className = 'close';
close.innerHTML = 'X';
div1.appendChild(close);
var timer = null;
var speedX = 3;
var speedY = 3;
var timer = setInterval(function() {
if (div1.offsetLeft + div1.offsetWidth >= document.documentElement.clientWidth || div1.offsetLeft <= 0) {
speedX = -speedX;
}
if (div1.offsetTop + div1.offsetHeight >= document.documentElement.clientHeight || div1.offsetTop <= 0) {
speedY = -speedY;
}
div1.style.left = div1.offsetLeft + speedX + 'px';
div1.style.top = div1.offsetTop + speedY + 'px';
}, 30);
div1.addEventListener('mouseover', function() {
clearInterval(timer);
});
div1.addEventListener('mouseout', function() {
timer = setInterval(function() {
if (div1.offsetLeft + div1.offsetWidth >= document.documentElement.clientWidth || div1.offsetLeft <= 0) {
speedX = -speedX;
}
if (div1.offsetTop + div1.offsetHeight >= document.documentElement.clientHeight || div1.offsetTop <= 0) {
speedY = -speedY;
}
div1.style.left = div1.offsetLeft + speedX + 'px';
div1.style.top = div1.offsetTop + speedY + 'px';
}, 30);
});
close.addEventListener('click', function() {
div1.parentNode.removeChild(div1);
});
在这个代码示例中,我们使用了一个定时器来实时改变div1的位置。当div1碰到浏览器边缘时,我们改变速度的方向,使其反弹回来。当鼠标移到div1上面时,我们清除定时器,暂停改变位置。当鼠标移开时,我们重新启动定时器。我们还在div1左上角添加了一个关闭按钮,点击后可以删除该div。
原文地址: https://www.cveoy.top/t/topic/mDcm 著作权归作者所有。请勿转载和采集!