一.純CSS實現圖片輪播ide
1)實現原理:函數
2)代碼示例:動畫
<div id="div1"> <div id="showImg"> <img src="img/video.png" width="1270px" height="390px"/> <img src="img/1.jpg" width="1270px" height="390px"/> <img src="img/2.jpg" width="1270px" height="390px"/> <img src="img/3.jpg" width="1270px" height="390px"/> <img src="img/4.jpg" width="1270px" height="390px"/> </div> </div>
#div1{ width:1270px;//此處寬高必須和圖片一致 height:390px; overflow: hidden; } #showImg{ height: 390px; width:9999px; animation: 8s lunbo infinite;//設置動畫時間週期,動畫執行函數,無限輪播 } #showImg img{ float:left;//使圖片水平排列 } @keyframes lunbo{ 0%{} 20%{transform: translateX(0px);} 25%{transform: translateX(-1270px);}//爲了加快圖片的過渡,5%的動畫執行時間 40%{transform: translateX(-1270px);} 45%{transform: translateX(-2540px);} 60%{transform: translateX(-2540px);} 65%{transform: translateX(-3810px);} 80%{transform: translateX(-3810px);} 85%{transform: translateX(-5080px);} 100%{transform: translateX(-5080px);} }
二.JS+CSS實現圖片輪播帶索引this
1)實現原理:spa
2)代碼示例:code
<div id="div1"> <div id="showImg"> <img src="img/video.png" width="1270px" height="390px"/> <img src="img/1.jpg" width="1270px" height="390px"/> <img src="img/2.jpg" width="1270px" height="390px"/> <img src="img/3.jpg" width="1270px" height="390px"/> <img src="img/4.jpg" width="1270px" height="390px"/> </div> <ul> <li class="selectedImg">1</li>//默認是第一張圖片的索引 <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </div>
#div1{ width:96%; height:390px; margin: 1% 2%; overflow: hidden;//超出邊框部分隱藏 position: relative; } #showImg{ position:absolute; height: 390px; width:9999px; left:0px; } #showImg img{ float:left; } #div1 ul{ position:absolute; bottom:15px; right:90px; } #div1 ul li{ background-color:black; color:white; list-style-type:none; width:25px; height:25px; float:left; font-size: 20px; text-align:center; cursor:pointer;//鼠標移動變手指狀態 margin-left:5px; } #div1 ul li.selectedImg{ background: orange;//給當前圖片的索引加背景顏色以示區分 }
var index = 0; var timer = null; function autoplay() { timer = setInterval(function() { $("#showImg").animate({left:-1270 * index}, 0);//left值每次改變一張圖片的寬度 $("#div1 ul li").eq(index).addClass("selectedImg").siblings().removeClass("selectedImg");//給當前索引加class index++; index >= 5 && (index = 0);//當index>=5爲假不執行index=0 }, 2000); } autoplay(); $("#div1").mouseover(function() { clearInterval(timer);//當鼠標移到圖片上暫停輪播 }) $("#div1").mouseleave(function() { autoplay();//鼠標移開繼續輪播 }) $(document).on("click","#div1 ul li",function(){//點擊索引跳到特定圖片 index = $(this).index(); $("#showImg").stop().animate({left:-1270 * index}, 10); $(this).addClass("selectedImg").siblings().removeClass("selectedImg"); })