重力运动

模拟重力运动,小球向下运动,速度依次增加,到达最大值时,转变方向,速度转变方向,大小损失,变为80%,当最后速度接近1时,直接让速度为0,位置定在最大值处,关闭定时器,完成重力运动。

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>重力运动</title>
<style type="text/css">
    *{
        padding: 0px;
        margin:0px;
    }
    #box{
        100%;
        height:500px;
        border-bottom: 3px solid black;
        position: relative;
    }
    #img{
        position: absolute;
        top:0px;
        left:30px;
        104px;
        height:100px;
    }
</style>
<script type="text/javascript">
window.onload=function(){
    var oqiu=document.getElementById('img');
    var obtn=document.getElementById('btn');
    obtn.onclick=function(){
        var speed=1;//设置速度变量
        timer=setInterval(function(){//定时器让小球动起来
            speed+=3;
            var old_top=oqiu.offsetTop;//获得就得top值
            var new_top=old_top+speed;//计算新的top值
            if(new_top>400){
                new_top=400;
                speed*=-0.8;//速度损失,并改变方向
            }
            if(-1<speed&&speed<1){
                speed=0;//当速度特别小时,直接变为0,防止抖动
            }
            if(speed==0&&new_top==400){
                clearInterval(timer);//当速度为0而且达到最大速度,关掉定时器
            }
            oqiu.style.top=new_top+'px';//赋值
        },10);
    }
}
</script>
</head>
<body>
<div id="box">
    <img src="qiu.jpg" alt="" id="img">
    <input type="button" id="btn" value="走你">
</div>    
</body>
</html>
原文地址:https://www.cnblogs.com/lzzhuany/p/4580512.html