效果如图:
原创代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>足球</title>
<style>
#ball{
position: absolute;
}
</style>
</head>
<body>
<img src="img/ball.png" id="ball"/>
<script>
var ball=document.getElementById("ball");
var height=window.innerHeight;//屏幕高
var width=window.innerWidth;
var ttop=0;
var lleft=0;
var flagud=true;//上下移动
var flaglr=true;//左右移动
function downupball(){
if(flagud){
dirmove("down",30);
if(ttop+ball.offsetHeight>=height){
flagud=false;
}
}else{
dirmove("up",30)
if(ttop<=0){
flagud=true;
}
}
}
function lrball(){
if(flaglr){
dirmove("right",20);
downupball();
if(lleft+ball.offsetWidth>=width){
flaglr=false;
}
}else{
dirmove("left",20);
downupball();
if(lleft<=0){
flaglr=true;
}
}
}
function dirmove(dir,speed){
switch(dir){
case "left":
lleft-=speed;
ball.style.left=lleft+"px";
break;
case "right":
lleft+=speed;
ball.style.left=lleft+"px";
break;
case "up":
ttop-=speed;
ball.style.top=ttop+"px";
break;
case "down":
ttop+=speed;
ball.style.top=ttop+"px";
break;
default:
break;
}
}
setInterval(lrball,100);
</script>
</body>
</html>