JavaScript 圖片滑動切換效果

序一(08/07/06)
看到alibaba的一個圖片切換效果,感覺不錯,想拿來用用。但代碼一大堆的,看着昏,還是自己來吧。
由於有了做圖片滑動展示效果的經驗,做這個就容易得多了。

序二(09/03/19)
自寫了Tween緩動之後就很想重新寫過這個效果,近來有點時間,終於可以動手了。
除了改成Tween緩動,也改進了程序算法,不過原理還是一樣的。

效果預覽
<script type="text/javascript">
var $ = function (id) {
  return "string" == typeof id ? document.getElementById(id) : id;
};

var Extend = function(destination, source) {
  for (var property in source) {
    destination[property] = source[property];
  }
  return destination;
}

var CurrentStyle = function(element){
  return element.currentStyle || document.defaultView.getComputedStyle(element, null);
}

var Bind = function(object, fun) {
  var args = Array.prototype.slice.call(arguments).slice(2);
  return function() {
    return fun.apply(object, args.concat(Array.prototype.slice.call(arguments)));
  }
}

var Tween = {
  Quart: {
    easeOut: function(t,b,c,d){
      return -c * ((t=t/d-1)*t*t*t - 1) + b;
    }
  },
  Back: {
    easeOut: function(t,b,c,d,s){
      if (s == undefined) s = 1.70158;
      return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
    }
  },
  Bounce: {
    easeOut: function(t,b,c,d){
      if ((t/=d) < (1/2.75)) {
        return c*(7.5625*t*t) + b;
      } else if (t < (2/2.75)) {
        return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
      } else if (t < (2.5/2.75)) {
        return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
      } else {
        return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
      }
    }
  }
}


//容器對象,滑動對象,切換數量
var SlideTrans = function(container, slider, count, options) {
  this._slider = $(slider);
  this._container = $(container);//容器對象
  this._timer = null;//定時器
  this._count = Math.abs(count);//切換數量
  this._target = 0;//目標值
  this._t = this._b = this._c = 0;//tween參數
    
  this.Index = 0;//當前索引
    
  this.SetOptions(options);
    
  this.Auto = !!this.options.Auto;
  this.Duration = Math.abs(this.options.Duration);
  this.Time = Math.abs(this.options.Time);
  this.Pause = Math.abs(this.options.Pause);
  this.Tween = this.options.Tween;
  this.onStart = this.options.onStart;
  this.onFinish = this.options.onFinish;
    
  var bVertical = !!this.options.Vertical;
  this._css = bVertical ? "top" : "left";//方向
    
  //樣式設置
  var p = CurrentStyle(this._container).position;
  p == "relative" || p == "absolute" || (this._container.style.position = "relative");
  this._container.style.overflow = "hidden";
  this._slider.style.position = "absolute";
    
  this.Change = this.options.Change ? this.options.Change :
    this._slider[bVertical ? "offsetHeight" : "offsetWidth"] / this._count;
};
SlideTrans.prototype = {
    //設置默認屬性
    SetOptions: function(options) {
  this.options = {//默認值
    Vertical:  true,//是否垂直方向(方向不能改)
    Auto:    true,//是否自動
    Change:    0,//改變量
    Duration:  50,//滑動持續時間
    Time:    10,//滑動延時
    Pause:    2000,//停頓時間(Auto爲true時有效)
    onStart:  function(){},//開始轉換時執行
    onFinish:  function(){},//完成轉換時執行
    Tween:    Tween.Quart.easeOut//tween算子
  };
  Extend(this.options, options || {});
    },
    //開始切換
    Run: function(index) {
  //修正index
  index == undefined && (index = this.Index);
  index < 0 && (index = this._count - 1) || index >= this._count && (index = 0);
  //設置參數
  this._target = -Math.abs(this.Change) * (this.Index = index);
  this._t = 0;
  this._b = parseInt(CurrentStyle(this._slider)[this.options.Vertical ? "top" : "left"]);
  this._c = this._target - this._b;
    
  this.onStart();
  this.Move();
    },
    //移動
    Move: function() {
  clearTimeout(this._timer);
  //未到達目標繼續移動否則進行下一次滑動
  if (this._c && this._t < this.Duration) {
    this.MoveTo(Math.round(this.Tween(this._t++, this._b, this._c, this.Duration)));
    this._timer = setTimeout(Bind(this, this.Move), this.Time);
  }else{
    this.MoveTo(this._target);
    this.Auto && (this._timer = setTimeout(Bind(this, this.Next), this.Pause));
  }
    },
    //移動到
    MoveTo: function(i) {
  this._slider.style[this._css] = i + "px";
    },
    //下一個
    Next: function() {
  this.Run(++this.Index);
    },
    //上一個
    Previous: function() {
  this.Run(--this.Index);
    },
    //停止
    Stop: function() {
  clearTimeout(this._timer); this.MoveTo(this._target);
    }
};
</script>
</head>
<body>
<style type="text/css">    
.container, .container img{width:280px; height:200px;}
.container{border:1px solid #333;}
.container img{border:0;}
</style>
<div class="container" id="idContainer">
  <table id="idSlider" border="0" cellpadding="0" cellspacing="0">
    <tr>
      <td><a href="http://www.cnblogs.com/cloudgamer/archive/2009/01/06/Tween.html"><img src="http://p_w_picpaths.cnblogs.com/cnblogs_com/cloudgamer/143727/r_rt_1.jpg"/></a></td>
    </tr>
    <tr>
      <td><a href="http://www.cnblogs.com/cloudgamer/archive/2008/07/21/ImgCropper.html"><img src="http://p_w_picpaths.cnblogs.com/cnblogs_com/cloudgamer/143727/r_rt_5.jpg"/></a></td>
    </tr>
    <tr>
      <td><a href="http://www.cnblogs.com/cloudgamer/archive/2008/11/17/Drag.html"><img src="http://p_w_picpaths.cnblogs.com/cnblogs_com/cloudgamer/143727/r_rt_3.jpg"/></a></td>
    </tr>
  </table>
</div>
<br />
<br />
<style type="text/css">
.num{ position:absolute; right:5px; bottom:5px;}
.num li{
  float: left;
  list-style:none;
  color: #fff;
  text-align: center;
  line-height: 16px;
  width: 16px;
  height: 16px;
  font-family: Arial;
  font-size: 12px;
  cursor: pointer;
  margin: 1px;
  border: 1px solid #707070;
  background-color: #060a0b;
}
.num li.on{
  line-height: 18px;
  width: 18px;
  height: 18px;
  font-size: 14px;
  border: 0;
  background-color: #ce0609;
  font-weight: bold;
}
</style>
<div class="container" id="idContainer2">
  <table id="idSlider2" border="0" cellpadding="0" cellspacing="0">
    <tr>
      <td><a href="http://www.cnblogs.com/cloudgamer/archive/2009/03/11/color.html"><img src="http://p_w_picpaths.cnblogs.com/cnblogs_com/cloudgamer/143727/r_4.jpg"/></a></td>
      <td><a href="http://www.cnblogs.com/cloudgamer/archive/2008/12/24/Slider.html"><img src="http://p_w_picpaths.cnblogs.com/cnblogs_com/cloudgamer/143727/r_3.jpg"/></a></td>
      <td><a href="http://www.cnblogs.com/cloudgamer/archive/2008/12/03/Resize.html"><img src="http://p_w_picpaths.cnblogs.com/cnblogs_com/cloudgamer/143727/r_rt_2.jpg"/></a></td>
    </tr>
  </table>
  <ul class="num" id="idNum">
  </ul>
</div>
<br />
<div>
  <input id="idAuto" type="button" value="停止" />
  <input id="idPre" type="button" value="<<" />
  <input id="idNext" type="button" value=">>" />
  <select id="idTween">
    <option value="0">默認緩動</option>
    <option value="1">方式1</option>
    <option value="2">方式2</option>
  </select>
</div>
<script>

new SlideTrans("idContainer", "idSlider", 3).Run();

///////////////////////////////////////////////////////////

var forEach = function(array, callback, thisObject){
  if(array.forEach){
    array.forEach(callback, thisObject);
  }else{
    for (var i = 0, len = array.length; i < len; i++) { callback.call(thisObject, array[i], i, array); }
  }
}

var st = new SlideTrans("idContainer2", "idSlider2", 3, { Vertical: false });

var nums = [];
//插入數字
for(var i = 0, n = st._count - 1; i <= n;){
  (nums[i] = $("idNum").appendChild(document.createElement("li"))).innerHTML = ++i;
}

forEach(nums, function(o, i){
  o. = function(){ o.className = "on"; st.Auto = false; st.Run(i); }
  o. = function(){ o.className = ""; st.Auto = true; st.Run(); }
})

//設置按鈕樣式
st.onStart = function(){
  forEach(nums, function(o, i){ o.className = st.Index == i ? "on" : ""; })
}

$("idAuto").onclick = function(){
  if(st.Auto){
    st.Auto = false; st.Stop(); this.value = "自動";
  }else{
    st.Auto = true; st.Run(); this.value = "停止";
  }
}
$("idNext").onclick = function(){ st.Next(); }
$("idPre").onclick = function(){ st.Previous(); }

$("idTween").onchange = function(){
  switch (parseInt(this.value)){
    case 2 :
      st.Tween = Tween.Bounce.easeOut; break;
    case 1 :
      st.Tween = Tween.Back.easeOut; break;
    default :
      st.Tween = Tween.Quart.easeOut;
  }
}


st.Run();
</script>



程序說明
原理就是通過不斷設置滑動對象的left(水平切換)和top(垂直切換)來實現圖片切換的動態效果。
首先需要一個容器,程序會自動設置容器overflow爲hidden,如果不是相對或絕對定位會同時設置position爲relative,
滑動對象會設置爲絕對定位:
var p = CurrentStyle(this._container).position;
== "relative" || p == "absolute" || (this._container.style.position = "relative");
this._container.style.overflow = "hidden";
this._slider.style.position = "absolute";

如果沒有設置Change切換參數屬性,會自動根據滑動對象獲取:
this.Change = this.options.Change ? this.options.Change :
    
this._slider[bVertical ? "offsetHeight" : "offsetWidth"/ this._count;

執行Run方法就會開始進入切換,其中有一個可選參數用來重新設置要切換的圖片索引:
index == undefined && (index = this.Index);
index 
< 0 && (index = this._count - 1|| index >= this._count && (index = 0);
之後就到設置使用tween緩動時需要的參數了,
包括_target(目標值)、_t(時間)、_b(初始值)和_c(變化量):
Code

還有Duration(持續時間)是自定義屬性。
參數設置好後就執行Move程序開始移動了。
裏面很簡單,首先判斷_c是否有值(等於0表示不需要移動)和_t是否到達Duration,
未滿足條件就繼續移動,否則直接移動到目標值並進行下一次切換:
Code
 
使用說明
實例化需要3個參數,分別是容器對象,滑動對象和切換數量,之後可以直接執行Run方法運行:
new SlideTrans("idContainer""idSlider"3).Run();

還有以下可選屬性:
Vertical: true,//是否垂直方向(方向不能改)
Auto:  true,//是否自動
Change:  0,//改變量
Duration: 50,//滑動持續時間
Time:  10,//滑動延時
Pause:  2000,//停頓時間(Auto爲true時有效)
onStart: function(){},//開始轉換時執行
onFinish: function(){},//完成轉換時執行
Tween:  Tween.Quart.easeOut//tween算子
其中Vertical初始化後就不能修改,Tween算子可參照這裏的緩動效果選擇(實例中選了其中3個)。
還有提供了以下方法:
Next: 切換下一個
Previous: 切換上一個
Stop: 停止自動切換
還有上面說到的Run
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章