ITPub博客

首页 > 应用开发 > > DOM运动的重力回弹+抛物线bug

DOM运动的重力回弹+抛物线bug

作者:cjk 时间:2019-08-14 14:18:25 0 删除 编辑

以下为页面代码,包含css,html,js

效果为一个原型的div在一个具有边框的大div中来回弹动

问题描述:

当上下的步长缩减为0.1时,在第二次弹到左边时,会飞出当前大框

将上下的步长缩减改为其他数值,问题时有发生

测试分析:

通过各种测试,问题出现的原因是因为小球同时在底部和左右弹动时发生问题

疑问点:

为什么会发生这个情况?

如何彻底解决这个问题?

<head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
        #cont{
            width: 1000px;height: 500px;
            margin: 50px auto;
            border: solid 1px black;
            position: relative;
        }
        #box{
            width: 100px;height: 100px;
            background: red;
            position: absolute;left: 0;
            border-radius: 50%;
        }
    </style>
</head>
<body>
    <div id="cont">
        <div id="box"></div>
    </div>
</body>
<script type="text/javascript">

    var ocont = document.getElementById("cont")
    var obox = document.getElementById("box")
    
    var speed = 10;
    var target = ocont.offsetHeight - obox.offsetHeight;
    var timer = null;
    
    var speedL = 50;
    var targetL = ocont.offsetWidth - obox.offsetWidth;
    
    var g = 1;
    
    ocont.onclick = function(){
        clearInterval(timer);
        timer = setInterval(function(){
            speed += g;
            if(target - obox.offsetTop < speed){
                obox.style.top = target + "px";
                speed = -(speed)*0.8;
                if(Math.abs(speed) < 1){
                    clearInterval(timer)
                }
            }else{
                obox.style.top = obox.offsetTop + speed + "px";
                obox.style.left = obox.offsetLeft + speedL + "px";
            }
            if(targetL - obox.offsetLeft < speedL){
                obox.style.left = targetL + "px";
                speedL = -speedL
            }
            if(Math.abs(0 - obox.offsetLeft) < Math.abs(speedL)){
                obox.style.left = "0";
                speedL = -speedL
            }
        },100)
    }
</script>


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4715/viewspace-3161764/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-29

  • 博文量
    181
  • 访问量
    1131