使用Require.js封装原生js轮播图的实现代码

index.html页面:





require.js封装轮播图





  

get.js代码如下:

define(function(require,exports,module){
  exports.getStyle = function (obj,name){
    if(obj.currentStyle){
      return obj.currentStyle[name];
    }else{
      return getComputedStyle(obj,false)[name];
    };
  };
});

init.js代码如下

require(['slider'],function(mod){
  mod.slide();
});

slider.js代码如下

define(function(require, exports, module) {
  var move = require('StartMove');
  var aBtn = document.getElementById('banner').getElementsByTagName('span');
  var oUl = document.getElementById('banner').getElementsByTagName('ul')[0];
  var aLi = oUl.children;
  //三张图片所占的宽度,length返回的是字符串中的字符数
    oUl.style.width = aLi.length * aLi[0].offsetWidth + 'px';
    exports.slide = function() {
      for(var i = 0; i < aBtn.length; i++) {
        aBtn[i].index = i;
        aBtn[i].onclick = function() {
          for(var i = 0; i < aBtn.length; i++) {
            aBtn[i].className = '';
          }
        aBtn[this.index].className = 'on';
          move.move(oUl, {
          left: -this.index * aLi[0].offsetWidth;
        });
      };
    };
  };
});

StartMove.js代码如下

define(function(require, exports, module) {
  var get = require('get');
  exports.move = function move(obj, json, complete) {
    clearInterval(obj.timer);
    var complete = complete || {};
    complete.dur = complete.dur || 1000;
    complete.easing = complete.easing || 'ease-out';
    var count = parseInt(complete.dur / 30); //总次数
    var start = {}; //{width:300,height:300}
    var dis = {};
    //{width:300,height:300}
    for(var name in json) {
      start[name] = parseFloat(get.getStyle(obj, name));
      dis[name] = json[name] - start[name];
    }
    var n = 0; //当前步数
    obj.timer = setInterval(function() {
    n++;
    for(var name in json) {
      var a = n / count;
      switch(complete.easing) {
        case 'linear':
        var cur = start[name] + a * dis[name];
        break;
        case 'ease-in':
        var cur = start[name] + Math.pow(a, 3) * dis[name];
        break;
        case 'ease-out':
        var a = 1 - n / count;
        var cur = start[name] + (1 - Math.pow(a, 3)) * dis[name];
        break;
      };
      if(name == 'opacity') {
          obj.style[name] = cur;
          obj.style.filter = 'alpha(' + cur * 100 + ')';
        } else {
          obj.style[name] = cur + 'px';
        };
      };
      if(n == count) {
        clearInterval(obj.timer)
        complete.fn && complete.fn();
      };
    }, 30);
   };
 });

以上所述是小编给大家介绍的使用Require.js封装原生js轮播图,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

你可能感兴趣的:(使用Require.js封装原生js轮播图的实现代码)