JS类与初始化,实例化使用

我们现在只是介绍两种不同的运动算法,当然运动算法还要很多,我们不意义例举,我们接着看如何写改变属性的js

首先我们定义一个运动类

var Animate = function ( dom ) {

            this.dom = dom;

            this.startTime = 0;

            this.startPos = 0;

            this.endPos = 0;

            this.propertyName = null;

            this.easing = null;

            this.duration = null;

 }

主要是初始化一些数据,然后我们在Animate的原型上定义一个start方法,该方法表示运动开始

Animate.prototype.start = function ( propertyName,endPos,duration,easing ){

      this.startTime = +new Date;//记录现在的开始时间

      this.startPos = this.dom.getBoundingClientRect()[ propertyName ];//记录开始的位置

      this.propertyName = propertyName;//需要改变的属性(传)

      this.endPos = endPos;//得到目标位置(传)

      this.duration = duration;//得到需要的时间(传)

      this.easing = tween[ easing ]//选择哪种运动的算法(传)

          var self = this;

          var timeId = setInterval(function(){

              //如果self返回false,则取消定时器

              if( self.step()=== false ) {

                  clearInterval( timeId )

              }

          },19)

 }

  上面的setInterval每隔19毫秒就会执行一次,每次都是执行step方法,step方法就是每次需要计算更新小球的位置

Animate.prototype.step = function(){

        //目前的时间

        var t = +new Date;

        //如果时间超过开始时间和需要时间之和,则矫正目前的位置为目标位置

        if( t >= this.startTime + this.duration ) {

                this.update( this.endPos )

                return false;//返回false为了取消定时器

        }

        //计算小球的位置

        var pos = this.easing( t - this.startTime, this.startPos, this.endPos-this.startPos ,this.duration)

        //更新div的属性

        this.update( pos )

}   

  那么update方法也仅仅就是更新div的属性而已

//更新当前位置

 Animate.prototype.update = function( pos ){

       this.dom.style[ this.propertyName ] = pos + 'px'

 }

  接下来我们看看我们在html里面如何执行,html代码

1<div style="position: absolute;background: blue;width: 100px;height: 100px;left: 0;" id="div"></div>

  然后是执行代码

var div = document.getElementById('div')

var animate = new Animate( div )

animate.start('left',500,5000,'linear')

  到现在我们整个运动就结束了

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 单例模式 适用场景:可能会在场景中使用到对象,但只有一个实例,加载时并不主动创建,需要时才创建 最常见的单例模式,...
    Obeing阅读 6,423评论 1 10
  • 1、策略模式的定义是: 定义一系列的算法, 把它们一个个封装起来, 并且使它们可以相互替换。 不变的部分和变化的部...
    spfi阅读 4,993评论 0 100
  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些阅读 6,169评论 0 2
  • 概要 64学时 3.5学分 章节安排 电子商务网站概况 HTML5+CSS3 JavaScript Node 电子...
    阿啊阿吖丁阅读 13,142评论 0 3
  • 来自西安的小刘【践行】第三十一天。作业:如何理解成熟。 成熟是不是思想指挥形动(想了在做)而不是行动指挥思想(做了...
    德罗巴007_592阅读 4,444评论 6 49