jQuery實現的簡單圖片輪播效果完整樣本,jquery實現樣本
本文執行個體講述了jQuery實現的簡單圖片輪播效果。分享給大家供大家參考,具體如下:
先來看看運行效果:
具體代碼如下:
<!DOCTYPE html><html><head><title>jquery實現圖片輪播效果</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><script src="http://www.bkjia.com/uploads/allimg/180212/021G21427-1.jpg"></li> <li><img src="http://www.bkjia.com/uploads/allimg/180212/021G26442-2.jpg"></li> <li><img src="http://www.bkjia.com/uploads/allimg/180212/021G21445-3.jpg"></li> <li><img src="http://www.bkjia.com/uploads/allimg/180212/021G21448-4.jpg"></li> <li><img src="http://www.bkjia.com/uploads/allimg/180212/021G21E0-5.jpg"></li> </ul></div><script type="text/javascript">$(document).ready(function(){ var oLi = $("li"); var liWidth = oLi.eq(0).width(); var liHeight = oLi.eq(0).height(); //每隔3秒進行輪播 var timer = setInterval(change,3000); //滑鼠放置在圖片上時停止輪播,移開時繼續輪播 $("div").mouseover ( function(){ clearInterval(timer); }) $("div").mouseout (function(){ timer = setInterval(change,3000); }) //輪播函數 var prevIndex = 0,nextIndex = 1; function change(){ if (prevIndex == oLi.length-1 ) {//若當前圖片是最後一張圖片,下一張出現首張圖片 nextIndex = 0; } var n = Math.floor(Math.random()*3); if (n == 0) { fade(prevIndex,nextIndex); } else if (n== 2) { slide(prevIndex,nextIndex); } else{ grap(prevIndex,nextIndex); } prevIndex = nextIndex; nextIndex ++; } //淡入淡出效果, function fade(prevIndex,nextIndex){ //傳入當前顯示圖片以及下一張圖片的索引 oLi.eq(prevIndex).fadeOut(1000); oLi.eq(nextIndex).fadeIn(1000); } //向左右滑動效果 function slide(prevIndex,nextIndex){ var rand = Math.floor(Math.random()*2); oLi.eq(nextIndex).show(); oLi.eq(nextIndex).css("z-index","-1"); if (rand) { //向左滑動 oLi.eq(prevIndex).animate({left: -liWidth},1000,fun); } else{ oLi.eq(prevIndex).animate({left: liWidth},1000,fun); } function fun(){ oLi.eq(prevIndex).css({"left":"0","display":"none"}); oLi.eq(nextIndex).css("z-index","1"); } } //收縮效果 function grap(prevIndex,nextIndex){ var rand = Math.floor(Math.random()*4); oLi.eq(nextIndex).show(); oLi.eq(nextIndex).css("z-index","-1"); switch (rand){ case 0://向左上方滑動 oLi.eq(prevIndex).animate({left: -liWidth,top: -liHeight},1000,function(){ oLi.eq(prevIndex).css({"left":"0","top": "0","display":"none"}); oLi.eq(nextIndex).css("z-index","1"); });break; case 1://向右上方滑動 oLi.eq(prevIndex).animate({left: liWidth,top: -liHeight},1000,function(){ oLi.eq(prevIndex).css({"left":'0',"top":"0","display":"none"}); oLi.eq(nextIndex).css("z-index","1"); });break; case 2://向右下角滑動 oLi.eq(prevIndex).animate({left: liWidth,top: liHeight},1000,function(){ oLi.eq(prevIndex).css({"left":'0',"top":"0","display":"none"}); oLi.eq(nextIndex).css("z-index","1"); });break; case 3://向左下角滑動 oLi.eq(prevIndex).animate({left: -liWidth,top: liHeight},1000,function(){ oLi.eq(prevIndex).css({"left":'0',"top":"0","display":"none"}); oLi.eq(nextIndex).css("z-index","1"); });break; default:break; } } });</script></body></html>