帮我写一个通过js定时器实时改变div2的位置大小为100px 30px背景为红底色要达到碰到浏览器边缘就反弹回来鼠标移到div2上面就暂停改变位置div1左上角还有关闭功能。都写在一个html里
<!DOCTYPE html>
<html>
<head>
<title>Div2动画效果</title>
<style>
#div1 {
position: absolute;
top: 0;
left: 0;
width: 20px;
height: 20px;
background-color: #ccc;
cursor: pointer;
}
#div2 {
position: absolute;
top: 50%;
left: 50%;
margin-top: -15px;
margin-left: -50px;
width: 100px;
height: 30px;
background-color: red;
border-radius: 5px;
animation: move 2s linear infinite;
cursor: pointer;
}
@keyframes move {
0% {
top: 50%;
left: 50%;
}
50% {
top: 0;
left: 0;
}
100% {
top: 50%;
left: 50%;
}
}
</style>
</head>
<body>
<div id="div1" onclick="closeDiv1()"></div>
<div id="div2" onmouseover="stopAnimation()" onmouseout="startAnimation()"></div>
<script>
var div2 = document.getElementById("div2");
var timer;
<pre><code> function startAnimation() {
timer = setInterval(function(){
var top = div2.offsetTop;
var left = div2.offsetLeft;
var width = div2.offsetWidth;
var height = div2.offsetHeight;
var clientWidth = document.documentElement.clientWidth;
var clientHeight = document.documentElement.clientHeight;
if (left <= 0 || left >= clientWidth - width) {
div2.style.left = left <= 0 ? 0 : clientWidth - width + "px";
}
else {
div2.style.left = left + 5 + "px";
}
if (top <= 0 || top >= clientHeight - height) {
div2.style.top = top <= 0 ? 0 : clientHeight - height + "px";
}
else {
div2.style.top = top + 5 + "px";
}
}, 10);
}
function stopAnimation() {
clearInterval(timer);
}
function closeDiv1() {
document.body.removeChild(document.getElementById("div1"));
}
startAnimation();
</script>
</code></pre>
</body>
</html>
原文地址: http://www.cveoy.top/t/topic/bcGL 著作权归作者所有。请勿转载和采集!