zoukankan      html  css  js  c++  java
  • 练习:javascript-setInterval动画运动平移,定时器动画练习

    常见问题:定时器加速问题,每次点击会启动一个定时器,解决先清除定时器

    
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>动画运动平移</title>
        <style>
            *{margin:0;padding:0;}
            #aa1 {position:absolute;left:0px;width:100px;height:100px;background:#F00;display:inline-block;}
            #btn1 {position:absolute;top:120px;}
            .line {position:absolute;left:300px;width:1px;height:500px;background:#000;}
        </style>
    </head>
    <body>
    <input type="button"  value = "移动" id="btn1">
    <div id="aa1"></div>
    <div id="aa2"></div>
    <div class='line'></div>
    <script>
        //1、定时器加速问题,每次点击会启动一个定时器,解决先清楚
        var oBtn1 = document.querySelector('#btn1');
        var oDiv1 = document.querySelector('#aa1');
        var timer=null;
        oBtn1.onclick=function(){
            clearInterval(timer);
            //2、不想改变speed值,判断起始值在目标点的方向
            (300-oDiv1.offsetLeft)<0? speed=-9: speed=9;
            timer = setInterval(function(){
                //3、距离足够近时,设置值
                 if(Math.abs(300-oDiv1.offsetLeft)<Math.abs(speed)){
                    oDiv1.style.left=300+'px';
                    clearInterval(timer);
                    timer =null;
                }else {
                     oDiv1.style.left =oDiv1.offsetLeft+speed+'px';
                 }
            },20)
        }
    </script>
    </body>
    </html>
    
    

    动画通用步骤:
    1:判断速度speed正负:
    (目标值-oDiv1.offsetLeft)<0? speed=负: speed=正;
    2、归位
    if(Math.abs(目标值-oShare.offsetLeft)<Math.abs(speed)){//显示
             oDiv1.style.left =dest+'px';
             clearInterval(timer);
             timer = null;
     }else {
             oDiv1.style.left =oDiv1.offsetLeft+speed+'px';
    }
    
    
    
     
  • 相关阅读:
    POJ 3258 (NOIP2015 D2T1跳石头)
    POJ 3122 二分
    POJ 3104 二分
    POJ 1995 快速幂
    409. Longest Palindrome
    389. Find the Difference
    381. Insert Delete GetRandom O(1)
    380. Insert Delete GetRandom O(1)
    355. Design Twitter
    347. Top K Frequent Elements (sort map)
  • 原文地址:https://www.cnblogs.com/liubingyjui/p/10219147.html
Copyright © 2011-2022 走看看