js版弹力球实例

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>弹力球实例</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
body{
background-color: #E8F8F8;
}
img{
50px;
height: 50px;
position: absolute;
top: 0px;
left: 0px;
}
</style>
</head>
<body>
<img src="img/box.png" id="img"/>
<script type="text/javascript">
window.onload=function(){
var clientwidth=document.documentElement.clientWidth;
var clientheight=document.documentElement.clientHeight;
document.body.style.width=clientwidth;
document.body.style.height=clientheight;
var x=0;
var y=3;
var e=0;
var r=3;
var flog=true;
var flag=true;
var imgbox=document.getElementById("img");
function run(){
imgbox.style.top=x+'px';
imgbox.style.left=e+'px';
}
var set=setInterval(function(){
//方法一
if(x<clientheight-imgbox.offsetHeight&&flog==true){
x+=y;
}else{
flog=false;
x-=y;
if(x==0){
flog=true;
}
}
if(e<clientwidth-imgbox.offsetWidth&&flag==true){
e+=r;
}else{
flag=false;
e-=r;
if(e==0){
flag=true;
}
}


// 方法二
// x+=y;
// e+=r;
// if(x>clientheight-imgbox.offsetHeight){
// x=clientheight-imgbox.offsetHeight;
// y=-y;
// }
// if(x<0){
// y=-y;
// }
// if(e>clientwidth-imgbox.offsetWidth){
// e=clientwidth-imgbox.offsetWidth;
// r=-r;
// }
// if(e<0){
// r=-r;
// }

run();
},1);
}
</script>
</body>
</html>

原文地址:https://www.cnblogs.com/luoguixin/p/6216401.html