zoukankan      html  css  js  c++  java
  • 第57天:匀速运动封装函数

    一、动画的原理

     动画的基本原理 让盒子的 offsetLeft   +  步长

    Math.abs(-5)   取绝对值函数

    二、匀速运动封装函数

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>匀速动画封装</title>
     6     <style>
     7         div{
     8             width: 100px;
     9             height: 100px;
    10             background-color: yellow;
    11             position: absolute;
    12         }
    13     </style>
    14 </head>
    15 <body>
    16 <button id="btn1">200</button>
    17 <button id="btn2">400</button>
    18 <div id="box"></div>
    19 </body>
    20 </html>
    21 <script>
    22     var btn1=document.getElementById("btn1");
    23     var btn2=document.getElementById("btn2");
    24     var box=document.getElementById("box");
    25     btn1.onclick=function(){
    26         animate(box,200);
    27     }
    28     btn2.onclick=function(){
    29         animate(box,400);
    30     }
    31     //封装匀速运动
    32     function animate(obj,target){
    33         var speed=obj.offsetLeft < target ? 5 : -5;//用来判断是+还是-
    34         obj.timer=setInterval(function(){
    35             var result=target-obj.offsetLeft;//差值不会大于5
    36             obj.style.left=obj.offsetLeft+speed+"px";
    37             if(Math.abs(result)<=5){//如果差值不小于5 到位置了
    38                 clearInterval(obj.timer);
    39                 obj.style.left=target+"px";//有5px差距直接跳转
    40             }
    41         },20)
    42     }
    43 </script>
  • 相关阅读:
    正则表达式学习网站
    Longest Substring Without Repeating Characters
    保留小数点后几位数字
    ReentrantLock和synchronized的区别随笔
    范型 小编
    两个线程交替打印字符串
    Gray Code
    Ajax
    堆排序
    Clone Graph
  • 原文地址:https://www.cnblogs.com/le220/p/7689493.html
Copyright © 2011-2022 走看看