HTML5+CSS3+JavaScript实现触碰边界自动反向运动的小球
源代码
<!DOCTYPE html>
<html>
<meta charset="utf8" />
<style>
.wp {
width: 600px;
height: 300px;
position: relative;
border: 1px solid black;
}
.box {
position: absolute;
width: 50px;
height: 50px;
background-color: rgb(216, 21, 21);
border-radius: 50%;
left: 0px;
top: 0px;
transition: all 0.1s;
}
</style>
<body>
<div class="wp" id="out">
<div class="box" id="box"></div>
</div>
<script>
//横速度
var width_speed = 10;
//纵速度
var height_speed = 10;
//绑定小球和外边盒子对象
var out = document.getElementById("out");
var box = document.getElementById("box");
//外边盒子宽高
var out_width = out.clientWidth;
var out_height = out.clientHeight;
//小球当前位置
var cache_width = box.offsetLeft;
var cache_height = box.offsetTop;
//定时器动画
var timer = setInterval(function () {
cache_width += width_speed;
cache_height += height_speed;
//如果触碰到边界,速度乘以-1,反向运动
if (cache_width >= out_width - box.offsetWidth || cache_width <= 0) {
width_speed *= -1;
}
if (cache_height >= out_height - box.offsetHeight || cache_height <= 0 ) {
height_speed *= -1;
}
//设置位置
box.style.left = cache_width + "px";
box.style.top = cache_height + "px";
}, 100);
</script>
</body>
</html>
评论 (0)