做一个网页动画,就是一个不停做直线(斜线方向)运动的小球,撞到屏幕边框后会反弹。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>小球</title>
<style>
.content{
width: 800px;
height: 400px;
border: 1px solid red;
position: absolute;
top: 50%;
left: 50%;
margin-top: -200px;
margin-left: -400px;
}
#ball{
width: 60px;
height: 60px;
background-color: pink;
border-radius: 30px;
position: absolute;
top:50%;
left: 0;
margin-top: -30px;
}
</style>
</head>
<body>
<div class="content">
<div id="ball"></div>
</div>
<script>
var ball=document.getElementById("ball");
var cont=document.getElementsByClassName("content")[0];
var contWidth=cont.clientWidth; // 包裹球的width
var ballWidth=ball.clientWidth; // 包裹球的henight
var contHeight=cont.clientHeight; // 球的width
var ballHeight=ball.clientHeight; // 球的height
var rightValue=60,topValue=60,x=true,y=true;// 横纵移动的初值和球运动方向
setInterval(test,1); //每隔1毫秒执行
function test(){
// 横向 left
if(x==true){
rightValue++;
if(rightValue>=(contWidth-ballWidth)){
x=false;
}
ball.style.left=rightValue+"px";
}else{
rightValue--;
if(rightValue<=0){
x=true;
}
ball.style.left=rightValue+"px";
}
// 纵向 top
if(y==true){
topValue++;
if(topValue>=contHeight-(ballHeight/2)){
y=false;
}
ball.style.top=topValue+"px";
}else{
topValue--;
if(topValue<=ballHeight/2){
y=true;
}
ball.style.top=topValue+"px";
}
};
</script>
</body>
</html>
浙公网安备 33010602011771号