2014-02-10 115 views
1

我在1個網站上使用此代碼3個畫廊。每個畫廊都有其他圖片。問題是第一個畫廊在循環中工作,但第二個和第三個畫廊在一個循環後停止。使用javascript的畫廊! 1個網站上的3個畫廊

<script type="text/javascript"> 
    function cycleImages(){ 
      var $active = $('#cycler .active'); 
      var $next = ($active.next().length > 0) ? $active.next() : $('#cycler img:first'); 
      $next.css('z-index',2);//move the next image up the pile 
      $active.fadeOut(1700,function(){//fade out the top image 
       $active.css('z-index',1).show().removeClass('active');//reset the z-index and unhide the image 
       $next.css('z-index',3).addClass('active');//make the next image the top one 
      }); 
     } 

    $(document).ready(function(){ 
    // run every 4s 
    setInterval('cycleImages()', 5000); 
    })</script> 

http://jsfiddle.net/eEpwK/3/

+0

如果你把小提琴/與代碼codepen演示你有什麼人都更願意和能夠提供幫助。 – surfmuggle

+1

我希望這個小提琴包含所有代碼那nessasary – donbenni

+0

問題upvote添加小提琴 – surfmuggle

回答

0

在你撥弄你使用的是id="cycler"多次。您可能已經知道,在一個頁面中,每個ID必須是唯一的。我做的第一件事就是改變你的HTML代碼,以這樣的:

<div id="one"> 
    <div id="cycler1" class="slides"> 
     ... 
    </div> 
</div> 
<div id="two"> 
    <div id="cycler2" class="slides"> 
     ... 
    </div> 
</div> 

由於IDS的循環儀現在不同(cycler1,cycler2,cycler3)我改變了CSS來此:

.slides { position:relative; } 
.slides img { position:absolute; z-index:1 } 
.slides img.active { z-index:3 } 

最後用javascript將它連接起來。這段代碼幾乎與您的差異一樣。代替將id選擇器#cylcer硬編碼到函數中,我傳遞了id選擇器作爲參數sel

function cycleImages(sel){            
    var $active = $(sel + " .active"); 
    var $next = ($active.next().length > 0) 
        ? $active.next() : $(sel + " img:first"); 
    //move the next image up the pile 
    $next.css('z-index',2); 
    //fade out the top image 
    $active.fadeOut(1700,function(){ 
     //reset the z-index and unhide the image 
     $active.css('z-index',1).show().removeClass('active'); 
     //make the next image the top one  
     $next.css('z-index',3).addClass('active'); 
    }); 
} 

現在,你只需要調用函數每個ID:

$(document).ready(function(){ 
    // run every 4s 
    // cycleImages(); 
    setInterval(function(){ 
       cycleImages("#cycler1"); 
       cycleImages("#cycler2"); 
       cycleImages("#cycler3") 
      }, 2000); 
}) 
+0

謝謝你所有這一切 – donbenni