帮我写一个通过js定时器实时改变div1的位置要达到碰到浏览器边缘就反弹回来鼠标移到div1上面就暂停改变位置div1左上角还有关闭功能。都写在一个html里
<!DOCTYPE html>
<html>
<head>
<title>Div动画效果</title>
<style type="text/css">
#div1 {
position: absolute;
top: 50px;
left: 50px;
width: 100px;
height: 100px;
background-color: red;
border-radius: 50%;
cursor: pointer;
}
</style>
</head>
<body>
<div id="div1"></div>
<script type="text/javascript">
var div1 = document.getElementById('div1');
var timer = null;
var speedX = 5;
var speedY = 5;
var stop = false;
<pre><code> // 改变div1位置
timer = setInterval(function() {
if (!stop) {
var left = div1.offsetLeft;
var top = div1.offsetTop;
if (left <= 0 || left >= document.documentElement.clientWidth - div1.offsetWidth) {
speedX = -speedX;
}
if (top <= 0 || top >= document.documentElement.clientHeight - div1.offsetHeight) {
speedY = -speedY;
}
div1.style.left = left + speedX + 'px';
div1.style.top = top + speedY + 'px';
}
}, 30);
// 点击关闭按钮
div1.onclick = function(event) {
var target = event.target;
if (target === div1) {
div1.style.display = 'none';
}
};
// 鼠标移动到div1上面
div1.onmouseover = function() {
stop = true;
};
// 鼠标移开div1上面
div1.onmouseout = function() {
stop = false;
};
</script>
</code></pre>
</body>
</html>
原文地址: http://www.cveoy.top/t/topic/bcGi 著作权归作者所有。请勿转载和采集!