輪播圖效果

輪播圖是頁面中常見的動畫效果css

本文經過 jQuery animate實現了簡單的5張圖片輪播效果html

實例效果:http://runjs.cn/code/dfdfoipt jquery

順便推薦一下 ,用RunJS來也頁面效果挺不錯的app

完整代碼函數

<html>
<script src="../jquery-1.11.0.min.js">
</script>
<style>
img{
  width:400px;
  height:200px;
  display:inline-block;
  }

.Carouse{
  margin-left:auto;
  margin-right:auto;
  overflow-x:hidden;
  position:absolute;
}
 .Carouse div {
  display:inline-block;
  float:left;
}
.Carouseparent{
 position:relative;
 width:400px;
 height:200px;
 overflow-x:hidden;
}

</style>
<body>
<div class="Carouseparent">
<div class="Carouse" style="left:-400px" >
   <div>
   <img src='../img/1.jpg'>
   </div>
   <div>
   <img src='../img/2.jpg'>
   </div>
   <div>
   <img src='../img/3.jpg'>
   </div>
   <div>
   <img src='../img/4.jpg'>
   </div>
   <div>
   <img src='../img/5.jpg'>
   </div>
</div>

</div>

<script>
 var imgwidth=400;
(function(){
 //初始時absolute div left 爲一個圖片的負數距離因此第一次執行動畫時
 //left 爲兩個負的圖片寬度 因此這裏index設爲一
 var index=1;
 var pipeCarouse = $(".Carouse");
 var firstCarouse = $(".Carouse >div").first();
 var lastCarouse= $(".Carouse >div").last()
 firstCarouse.clone(true).appendTo(pipeCarouse);
 lastCarouse.clone(true).prependTo(pipeCarouse);
 var CarouseItem = $(".Carouse >div");
 pipeCarouse.width (imgwidth * CarouseItem.length)
 //初始時absolute div left 爲一個圖片的負數距離因此第一次執行動畫時
 //left 爲兩個負的圖片寬度
 //五個圖片位 開始時顯示一張圖片 輪播四次就能把圖片播放完 傳入參數 2 3 4 5
 //到六時從新開始輪播 index 設爲1
 function Carouseanimate(i){
    pipeCarouse.animate({left:-i*imgwidth},400,function(){
    
	if(i==(CarouseItem.length)-1){
	  //從新開始 後面就是空白的div了
	  pipeCarouse.css("left",-imgwidth);
	  index=1;
	}
})
}

function setTimer(){
		timer = setInterval( function(){
		Carouseanimate( ++index );
		}, 2000 );
	}
	setTimer()
	
	
	$(".Carouseparent").on( "mouseover", function(){
		clearInterval( timer );
	})
	$(".Carouseparent").on("mouseout",function(){
	  setTimer();
	})
 
})()



</script>

</body>
</html>

實現過程動畫

   1  建兩個容器div 外層div定位 設置成relative(相對定位),裏層容器設置爲absolute(絕對定位)設計

<div class="Carouseparent">
<div class="Carouse" style="left:-200px" >
   <div>
   <img src='../img/1.jpg'>
   </div>  
</div>
</div>
<div class="Carouseparent">
<div class="Carouse" style="left:0px" >
   <div>
   <img src='../img/1.jpg'>
   </div>  
</div>
</div>

       能夠看出上面的圖有一部分沒有了(style="left:-200px"")code

       這說明了外層容器relative 裏層容器absolute的條件下 裏層容器設置left爲負值能夠實現圖片往左移而且移到父容器以外的元素消失,固然父容器的樣式得設置成橫軸溢出部分隱藏。htm

      2 咱們能夠想象父容器樣式設置爲寬度爲圖片寬度,橫軸超出部分隱藏,seo

       裏層容器設計成5張圖片連續在一塊兒而後改變裏層容器樣式中的left值,每次left減圖片寬度,這樣就能實現裏層容器想左移動的效果。

     這裏咱們每次移動一個元素,要在子容器中將最後一個元素移動懂第一個元素(Carouse 下 div),第一元素移動到最後一個元素後面,這樣是爲了防止移動到後面出現空白的狀況,若是每次移動兩個元素 那就要頭尾都複製兩個元素了

   div 原本是塊級元素的也就是沒一個div都會另起一行,這裏經過

.Carouse div {
  display:inline-block;
  float:left;
}

將子容器中的div設爲內聯元素 ,而且能夠設置寬度,這就將子容器中的元素所有放到同一行了

3 子容器初始left設爲-400px(400爲一個圖片寬度),這樣初始時刻頁面顯示的就是第一個圖片了。

   在子容器中綁定動畫函數animate 這個函數功能是改變子容器中的left值

<div class="Carouse" style="left:-400px" >

     設置定時函數 調用綁定animate動畫的函數實現輪播功能

相關文章
相關標籤/搜索