<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title>飄舞的小球</title> <style type="text/css"> div { width: 100px; height: 100px; line-height: 100px ...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>飄舞的小球</title>
<style type="text/css">
div {
width: 100px;
height: 100px;
line-height: 100px;
font-size: 30px;
border-radius: 50px;
background-color: cyan;
text-align: center;
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div id="piao">飄啊飄</div>
</body>
<script type="text/javascript">
// 設置變化速度
var xSpeed = 10
var ySpeed = 20
// 獲取變數
var piao = document.getElementById('piao')
// 獲取尺寸
var width = parseInt(getComputedStyle(piao)['width'])
var height = parseInt(getComputedStyle(piao)['height'])
// 設置周期定時任務
var timer = setInterval(function() {
// 獲取當前位置
var left = parseInt(getComputedStyle(piao)['left'])
var top = parseInt(getComputedStyle(piao)['top'])
// 設置新的位置
left += xSpeed
top += ySpeed
// 對當前位置進行判定,防止小球跑出邊界
if (left <= 0 || left + width >= window.innerWidth) {
xSpeed *= -1
}
if (top <= 0 || top + height >= window.innerHeight) {
ySpeed *= -1
}
// 寫入位置
piao.style.left = left + 'px'
piao.style.top = top + 'px'
},100)
</script>
</html>