本文實例講述了jQuery簡單自定義圖片輪播插件及用法。分享給大家供大家參考,具體如下:
經常使用別人的插件,現在自己寫一個,紀念一下。
jQuery.banner.js:
/*
* banner 0.1
* 使用banner 實現圖片定時切換 鼠標經過停止動畫
* 鼠標離開,繼續動畫
*/
;(function($){
$.fn.banner =function(options){
//各種屬性和參數
var defaults ={
picWidth:"1000",
picHeight:"300",
speed:"1500"
};
var totalW = 0; //保存總的動畫寬度
var timer = null; //保存定時器
var current = 0; //保存當前動畫到第N張圖,下次從這裡開始
var totalNum = 0; //保存總的圖數
var Dsqtime = 0; //定義定時器時間 【外傳參數】
var Dhtime = 0; //定義動畫時間
var count = 0 ;
//合並多個對象為一個,即有新參數 用新的,否則用默認的
var options = $.extend(defaults, options);
this.each(function(){
//實現代碼
var __this = $(this);
Dsqtime = options.speed;
Dhtime = Dsqtime/3;
//初始化
init(__this);
//調用動畫
show(__this, options.picWidth,current);
//鼠標經過時事件
__this.find('ul li').bind('mouseover',function(){
window.clearInterval(timer); //清除定時器
});
__this.find('ul li').bind('mouseout',function(){
show(__this, options.picWidth,current);
//接著上一次動畫輪播
});
});
//初始化 設定父容器寬度
function init(obj){
obj.find('ul li').each(function(){
totalW += $(this).width();
totalNum++;
});
obj.find('ul').width(totalW);
}
//開始動畫顯示
function show(obj, width, current){
timer = setInterval(function(){
obj.find('ul').animate({'margin-left':'-'+count*width+'px'},
Dhtime);
current = count;
count++;
if(count == totalNum){
count =0;
}
}, Dsqtime);
}
};
})(jQuery);
html代碼:
<!doctype html>
<html>
<head>
<meta charset="utf8"/>
<script type="text/javascript" src="./js/jquery.min.js"></script>
<script type="text/javascript" src="./js/jquery.banner.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.wrap').banner({
picWidth:"1000",
picHeight:"300",
speed:"6000"
});
});
</script>
<style type="text/css">
*{margin:0;padding:0;}
.wrap{width:1000px; height:300px; overflow:hidden; margin:0 auto;}
.wrap ul li{float:left; list-style:none;}
.wrap ul li img{width:1000px;height:300px;}
.clear{clear: both;}
</style>
</head>
<body>
<div>
<div class="wrap">
<ul>
<li><a href="#"><img src="./images/1.jpg"/></a></li>
<li><a href="#"><img src="./images/2.jpg"/></a></li>
<li><a href="#"><img src="./images/3.jpg"/></a></li>
<li><a href="#"><img src="./images/4.jpg"/></a></li>
<li><a href="#"><img src="./images/5.jpg"/></a></li>
</ul>
<div class="clear"></div>
</div>
</div>
</body>
</html>
效果圖:

更多關於jQuery相關內容感興趣的讀者可查看本站專題:《jQuery常用插件及用法總結》、《jQuery擴展技巧總結》、《jQuery切換特效與技巧總結》、《jQuery遍歷算法與技巧總結》、《jQuery常見經典特效匯總》、《jQuery動畫與特效用法總結》及《jquery選擇器用法總結》
希望本文所述對大家jQuery程序設計有所幫助。