效果預覽如下:
實現原理:
容器採用相對定位,圖片採用絕對位置,當滑鼠移動到相應的圖片上,改變去left屬性,用tween實現動畫效果.
程式碼分析:寫一個picSlider類實現代碼封裝
複製代碼 代碼如下:
<div id="container">
<img src="http://files.jb51.net/file_images/article/201104/r_song1.jpg" alt="" />
<img src="http://www.bkjia.com/uploads/allimg/131016/1HK51S7-2.jpg" alt="" />
<img src="http://www.bkjia.com/uploads/allimg/131016/1HK55U8-3.jpg" alt="" />
<img src="http://www.bkjia.com/uploads/allimg/131016/1HK55938-4.jpg" alt="" />
<img src="http://www.bkjia.com/uploads/allimg/131016/1HK53647-5.jpg" alt="" />
</div>
CSS樣式
複製代碼 代碼如下:
#container{width:459px; height:200px; background-color:Black;position:relative;overflow:hidden;}
#container img{position:absolute; width:360px;height:300px;display:block;top:0;width:280px;height:200px;}
JS:picSlider類
複製代碼 代碼如下:
var picSlider = new Class({
Implements: Options,
options: {
container: "container",
imgsWidth: 0.6,
},
initialize: function (options) {
this.setOptions(options);
this.container = $(this.options.container);
this.triggers = this.container.getElementsByTagName("img");
this.containerWidth = this.container.getSize().x; //get container's width
this.imgWidth = this.containerWidth * this.options.imgsWidth;
this.aveWidth = this.containerWidth / this.triggers.length;
this.newAveWidth = (this.containerWidth - this.imgWidth) / (this.triggers.length - 1);
this.setImgsInit(); //初始化圖片展示
this.start();
},
setImgsInit:function(){
for(var i=0;i<this.triggers.length;i++){
this.triggers[i].setStyle("left",i*this.aveWidth);
}
},
start:function(){
for(var i=0;i<this.triggers.length;i++){
this.triggers[i].set("tween",{property:"left",duration:300, fps:80}); //為每個元素設定動畫參數
this.triggers[i].addEvent("mouseover",this.slider.bindWithEvent(this,[i]));//綁定slider函數
}
},
slider:function(e,at){
e.stop();
for(var i=1;i<this.triggers.length;i++){
if(i<=at){
this.triggers[i].get("tween").start(i*this.newAveWidth);
}else{
this.triggers[i].get("tween").start(this.imgWidth+(i-1)*this.newAveWidth);
}
}
}
});
new picSlider();
如果想直接在本地運行,請引入
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/mootools/1.3.1/mootools-yui-compressed.js"></script>
<script type="text/javascript" src="home.js"></script>這個指令碼必須在<div><div>後面,原因不解釋!