js练习 弹球

球落下后每次弹起一半的高度,

<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style type="text/css">
*{ margin:0 auto; padding:0;}
#wai{ width:200px; height:500px; margin-top:50px;  position:relative;}
#qiu{ width:50px; height:50px; border-radius:50%; background-color:blue; margin-bottom:0px;}
#buttom{ width:100%; }
#top1{ width:100%; }
#zhan1{ width:100%;  }
#zhan2{ width:100%; }
</style>

</head>

<body>
    <div id="wai">
        <div id="zhan1" style="height:0%;"></div><!--用来限制每次的弹起高度-->
        <div id="zhan2" style="height:100%;"><!--用来限制每次的弹起高度,其高度就是球可以弹起的最大高度-->
            <div id="top1" style="height:0%;"></div><!--用来控制球的下落和弹起-->
            <div id="buttom" style="height:100%;"><!--用来控制球的下落和弹起-->
                <div id="qiu" sx="100"></div><!--属性sx用来控制和接收每次变化的值,sx可以为负数,绝对值和其父级高度的百分比数值相同-->
            </div>
        </div>
        
    </div>

</body>
</html>
<script type="text/javascript">
    var top1 = document.getElementById("top1");
    var buttom = document.getElementById("buttom");
    var zhan1 = document.getElementById("zhan1");
    var zhan2 = document.getElementById("zhan2");
    var qiu = document.getElementById("qiu");
    var th = parseInt(top1.style.height);
    var bh = parseInt(buttom.style.height);
    var zh1h = parseInt(zhan1.style.height);
    var zh2h = parseInt(zhan2.style.height);
    var ids;
    /*
        每隔0.5秒执行一次qiu()方法,间隔的id为到变量ids
    */
    qiu.onclick = function()
    {
        ids = window.setInterval("qiuX()",500);    
    }
    
    /*
        球下落再弹起一半高度
    */
    function qiuX()
    {
        var sx = qiu.getAttribute("sx");
        sx--;    //qiu的sx属性持续减一
        bh = Math.abs(sx);//bottom的高度等于sx的绝对值,完成反弹
        th = 100-bh;//bottom和top的高度和是100%
        qiu.setAttribute("sx",sx);//变化后的sx值重新赋予sx属性
        top1.style.height = th+"%";
        buttom.style.height = bh+"%";
        if(sx>-50)    //控制弹起的高度是落下高度的一半
        {
            window.setTimeout("qiuX()",10);
            
        }
        else if(sx==-50)//当弹起高度达到一半的时候sx属性、bottom的高度和top的高度重置,外层的zhan2每次缩小一半,当外层zhan2高度为0时清除间隔
        {
            zh2h = parseInt(zh2h/2);    
            zh1h = 100-zh2h;
            zhan1.style.height = zh1h+"%";
            zhan2.style.height = zh2h+"%";
            top1.style.height = 0;
            buttom.style.height = 100;
            qiu.setAttribute("sx",100);
            if(zh2h==0)
            {
                window.clearInterval(ids);
            }
        }
    }
</script>
原文地址:https://www.cnblogs.com/zxbs12345/p/8017234.html