zoukankan      html  css  js  c++  java
  • 重力回弹抛物线

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <style>
            .box{800px;height: 500px;border: solid 1px black;margin: 20px auto;position: relative;}
            .box div{100px;height:100px;background: red;border-radius: 50%;position: absolute;left: 0;top:0;}
        </style>
    </head>
    <body>
        <div class="box">
            <div></div>
        </div>
    </body>
    <script>
        var div = document.querySelector(".box div");
    
        // 计时器
        var t;
        // 底部目标
        var target = 400;
        // 垂直步长
        var speed = 2;
    
        // 水平步长
        var speedL = 20;
        // 右边的目标
        var targetR = 700;
    
        document.onclick = function(){
            clearInterval(t);
            t = setInterval(() => {
                // 重力加速
                speed++;//负的speed++会变成正的然后top越来越大最后执行if中语句。直接结束了
    
                // 是否到底
                if(target - div.offsetTop < speed){
                    div.style.top = target + "px";//下一次定时器执行时speed已经变成负的了,target - div.offsetTop不小于speed,执行else;
                    // 步长取反,实现回弹
                    speed = -speed * 0.9;
                    // 步长小于1,衰减的下限,可以停止计时器了
                    if(Math.abs(speed) < 1){
                        clearInterval(t)
                    }
                }else{
                    div.style.top = div.offsetTop + speed + "px";
                }
            console.log(div.style.top)
    
                // 右边目标判断
                if(targetR - div.offsetLeft < speedL){
                    div.style.left = targetR + "px"
                    // 步长取反,实现回弹
                    speedL = -speedL;
                        // 当前案例,水平的移动应根据垂直是否停止而决定
                }else if(Math.abs(speed) >= 1){
                    div.style.left = div.offsetLeft + speedL/2 + "px";
                }
                
                // 左边步长判断
                if(div.offsetLeft < 0){
                    div.style.left = 0;
                    // 步长取反,实现回弹
                    speedL = -speedL;
                        // 当前案例,水平的移动应根据垂直是否停止而决定
                }else if(Math.abs(speed) >= 1){//上下没听才能继续走
                    div.style.left = div.offsetLeft + speedL/2 + "px";
                }
                // console.log(speed);
            }, 30);
        }
    </script>
    </html>
  • 相关阅读:
    迭代器和生成器
    20.03.23作业
    装饰器
    集合
    元组类型
    字典类型
    列表类型
    字符串类型
    for循环
    深浅copy与while循环
  • 原文地址:https://www.cnblogs.com/hy96/p/11462007.html
Copyright © 2011-2022 走看看