• 原生JS封装时间运动函数


    /*讲时间运动之前先给大家复习一下运动函数

    通常大家都会写运动框架,一个定时器(Timer),一个步长(step 就是每次运动的距离),一个当前位置(current)一个目标位置(target),然后判断一下当前位置加上步长和目标位置的关系就可以了

    就可以了。

    简写就是这样呗*/

    var obj=document.getElementById("div");

    /*想要获取元素当前的位置,是要获取CSS的,obj.style.left="25"px;这样是OK的,没有问题,

    但是如果你这么写 var left=obj.style.left;是获取不到的,CSS的获取,需要用到方法*/

    function getCSS(obj,attr){

    /*window.getComputedStyle 兼容标准浏览器  谷歌 火狐 苹果浏览器

    currentStyle 是兼容IE的*/

    return window.getComputedStyle?getComputedStyle(obj)[attr]:obj.currentStyle[attr];

    }

    /*attr 是要改变的元素属性(left或者top);

    step的正负决定运动方向*/

    function move(obj,target,step,attr)

    {

    var timer=null,current=0;

    clearInterval(timer);

    timer=setInterval(function(){

     current=parseFloat(getCSS(obj,attr));//去掉单位px

      if((current+step-target)*step<0) //运动向下或者向上都满足这个条件

    {   

      obj.style[attr]=current+step+"px";

    }

    else{

     obj.style[attr]=target+"px";

     clearInterval(timer);

    }

    },1000/60);

    }

    时间运动函数

    function getCSS(obj,attr){
    return window.getComputedStyle?window.getComputedStyle(obj)[attr]:obj.currentStyle[attr];
    }

    function $(id){return document.getElementById(id);}
    /*时间运动主要依赖一个公式 变化的时间/总时间=变化的位移/总位移
    当比值为1的时候,运动就结束了呗!
    变化的时间=当前时间-初始的时间
    变化的位置=当前位置-初始位置
    每次移动的位移=(变化的时间/总时间)*总位移
    */

    function move(obj,attr,time,target)
    {
    var current=parseFloat(getCSS(obj,attr));//获取当前位置
    var startTime=new Date();//获取当前时间
    var offset=target-current;//总偏移量,总位移
    var changeTime=0;//变化的时间
    obj.timer=null;
    clearInterval(obj.timer);//使用定时器之前清除一下,只是一个良好的习惯,避免多次产生定时器

    obj.timer=setInterval(function(){
    changeTime=(new Date()-startTime);//变化的时间
    var t=changeTime/time;//变化的时间/总时间
    if(t>=1){

    obj.style[attr]=target+"px";
    clearInterval(obj.timer);

    }

    else{
    obj.style[attr]=current+t*offset+"px";

    }
    },1000/60);

    }

    经过测试都是没问题的 

  • 相关阅读:
    解决Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.j...
    Docker容器无法启动,里面的配置文件如何修改
    C# lamada find
    【Redis】arm64架构,docker的Redis出现Failed to test the kernel for a bug that could lead to data corruption
    启动Docker容器报错:Error response from daemon: driver failed programming external connectivity
    redis OCI runtime exec failed: exec failed:解决方法
    如何远程访问 Redis
    nanopi r2c上docker安装甜糖
    Net6 EfCore 值对象类型和从属实体类型
    Net6 控制台程序引入Nlog 、Nlog配置文件解读
  • 原文地址:https://www.cnblogs.com/liveoutfun/p/8733155.html
Copyright © 2020-2023  润新知