zoukankan      html  css  js  c++  java
  • 原生JS实现前端动画框架

    封装了一个JS方法,可支持块元素的常规动画:高、宽、透明度、位置等,同时支持链式动画和同时运动,参照imooc整理,具体代码如下:

    /**
    * 获取HTML元素属性值
    * obj是Element, attr是属性
    **/
    function getStyle(obj, attr) {
    if (obj.currentStyle) {
      // IE浏览器
      return obj.currentStyle[attr]; 
     } else {
      // Google、Firefox等
      return getComputedStyle(obj, false)[attr];
    }
    }
    /**
    * 主函数,实现元素动画。
    * obj是Element, attrJson是属性及其目标值的JSON,fn是运动完成后的回调函数,根据回调函数实现链式动画
    */
    function startMove(obj, attrJson, fn) {
     // 1. 清空该元素的定时器
    clearInterval(obj.timer);
    // 变量flag 记录运动是否需要停止
    var flag = true;
     // 2. 开启该元素的定时器,间隔时间可重设
     obj.timer = setInterval(function() {
    // 遍历attrJson,获取需要运动的属性,对每个属性进行改变
      for (var attr in attrJson) {
    // 属性目标值
    var iTarget = attrJson[attr];
    // 获取原本属性值
    var iCur = 0;
    if (attr == 'opacity') {
         // 对透明度(opacity)单独处理
    iCur = Math.round(parseFloat(getStyle(obj, attr)) * 100);
    } else {
    iCur = parseInt(getStyle(obj, attr));
    }
    // 判断此属性的运动是否已经完成
    if (iTarget == iCur) {
    continue;
    }
    flag = false;
    // 8为速度系数,可重设
    var speed = (iTarget - iCur) / 8;
    speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
    if (attr == 'opacity') {
    obj.style.filter = 'alpha(opacity:' + (iCur + speed) + ')';
    obj.style[attr] = (iCur + speed)/100;
    } else {
    obj.style[attr] = iCur + speed + 'px';
    }
    }
    // 全部属性均已经运动完成
    if (flag) {
    clearInterval(obj.timer);
    // 如果有回调函数,开启下一个回调函数
    if (fn) {
    fn();
    }
    }
     }, 30);
    }

    调用代码如下:

    window.onload = function() {
    var li1 = document.getElementById("li1");
    li1.onmouseover = function() {
    startMove(this, {400, height:200, opacity:100});
    };
    li1.onmouseout = function() {
    startMove(this, {200, height:100, opacity:30});
    }
    }

  • 相关阅读:
    SuperMap房产测绘成果管理平台
    SuperMap产权登记管理平台
    Android adb shell am 的用法(1)
    由浅入深谈Perl中的排序
    Android 内存监测和分析工具
    Android 网络通信
    adb server is out of date. killing...
    引导页使用ViewPager遇到OutofMemoryError的解决方案
    adb logcat 详解
    How to send mail by java mail in Android uiautomator testing?
  • 原文地址:https://www.cnblogs.com/effortn/p/10246033.html
Copyright © 2011-2022 走看看