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';
    }
    
    
    
     
  • 相关阅读:
    测试一下你的T-SQL基础知识-count
    测试一下你的T-SQL基础知识-subquery
    Microsoft SQL Server 2012 管理 (2): Auditing
    Webpack
    react
    Webpack 傻瓜式指南(一)
    谈谈react-router学习
    使用Flexible 实现手淘H5 页面的终端适配学习
    Promise 让异步更优
    基于LeanCloud云引擎的Web全栈方案
  • 原文地址:https://www.cnblogs.com/liubingyjui/p/10219147.html
Copyright © 2011-2022 走看看