萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript + CSS 實現圖片動態切換輪播(含導航點)

效果預覽

點擊下方導航圓點/數字,主圖區域平滑切換對應圖片,當前導航高亮。

CSS 佈局 (index.css)

* { margin:0; padding:0; }
body { width:632px; margin:0 auto; }
#imgsCom { background:yellow; position:relative; }
#ulnav { list-style:none; position:absolute; bottom:0; right:0; }
#ulnav li { float:left; background:black; color:white; margin-right:5px; width:20px; height:20px; line-height:20px; text-align:center; cursor:pointer; }

HTML 結構 (index.html)

<div id="imgsCom" style="width:632px;height:412px;">
  <img src="images/1.png" id="myimg" style="width:632px;height:412px;" />
  <ul id="ulnav">
    <li>1</li><li>2</li><li>3</li>
  </ul>
</div>

JS 邏輯

<script>
function gel(id){ return document.getElementById(id); }
function clearLiBg(){
  var lis = gel("ulnav").childNodes;
  for(var i=0;i

進階:自動輪播 + 淡入淡出

var idx = 0, timer;
var imgs = ["1.png","2.png","3.png"];
function autoPlay(){
  timer = setInterval(function(){
    idx = (idx+1)%imgs.length;
    switchImg(idx);
  }, 3000);
}
function switchImg(i){
  $("#myimg").fadeOut(300, function(){
    this.src = "images/"+imgs[i];
    $(this).fadeIn(300);
  });
  clearLiBg();
  $("#ulnav li").eq(i).css("background","silver");
}
$("#ulnav li").click(function(){
  clearInterval(timer);
  switchImg($(this).index());
  autoPlay();
});
autoPlay();
copyright © 萬盛學電腦網 all rights reserved