<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Document</title> | |
<style> | |
* { | |
margin: 0; | |
padding: 0; | |
} | |
.box1 { | |
margin: 20px auto; | |
position: relative; | |
width: 500px; | |
height: 400px; | |
border: 2px solid blue; | |
} | |
.box2 { | |
position: absolute; | |
width: 30px; | |
height: 30px; | |
border-radius: 50%; | |
background-color: red; | |
} | |
.start { | |
margin-left: 200px; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="box1"> | |
<div class="box2"></div> | |
</div> | |
<button class="start">开始</button> | |
<button class="suspended">暂停</button> | |
<script> | |
var box1 = document.querySelector('.box1'); | |
var box2 = document.querySelector('.box2'); | |
var start = document.querySelector('.start'); | |
var suspended = document.querySelector('.suspended'); | |
start.onclick = function () { | |
start.disabled = true; | |
var event = event || window.event; | |
var myLeft =0; | |
var myTop = 0; | |
var flag1 = true; | |
var flag2 = true; | |
var timer = setInterval(function () { | |
box2.style.left = myLeft + 'px'; | |
box2.style.top = myTop + 'px'; | |
if (flag1) { | |
myLeft++; | |
} else { | |
myLeft--; | |
} | |
if (flag2) { | |
myTop++; | |
} else { | |
myTop--; | |
} | |
if (myLeft >= box1.clientWidth - box2.clientWidth) { | |
flag1 = false | |
} else if (myLeft <= 0) { | |
flag1 = true | |
} | |
if (myTop >= box1.clientHeight - box2.clientHeight) { | |
flag2 = false | |
} else if (myTop <= 0) { | |
flag2 = true | |
} | |
}, 4) | |
suspended.onclick = function () { | |
start.disabled = false; | |
clearInterval(timer); | |
} | |
} | |
</script> | |
</body> | |
</html> |
JS触壁反弹动画
最新推荐文章于 2024-07-12 16:27:40 发布