2010-08-21 48 views
0

我需要在我的網站上循環瀏覽4個圖像,我不想在網站上添加另一個插件,所以我創建了自己的簡單傳送帶(html,css和js)優化一個簡單的jQuery圖像傳送帶

我的問題是,僅僅從看這段代碼,有沒有一種明顯更簡單/更好的方法來做到這一點?

HTML:

<section id="carousel"> 
    <img src="images/image_00.jpg" width="202" height="162" /> 
</section> 

CSS:

#carousel{text-align:center;position:relative;} 
#carousel img{top:0;left:0;z-index:1;position:absolute;} 

JS:

function carousel(el, base_url, images, i){ 
    if (i == images.length) i = 0; 
    var el2 = $(el).clone(); 
    $(el).css('z-index', '1'); 
    el2.css('z-index', '0'); 
    el2.attr('src', base_url + images[i]); 
    $(el).after(el2); 
    $(el).fadeOut('slow', function(){ 
     $(this).remove(); 
    }); 
    i++; 
    var func = function(){return carousel(el, base_url, images, i);}; 
    window.timer = setTimeout(func, 4000); 
} 
$(document).ready(function(){ 
    carousel('#carousel img:first', 
      'images/', 
      ['image_00.jpg', 
       'image_01.jpg', 
       'image_02.jpg', 
       'image_03.jpg'], 
      0); 
}); 
+0

爲什麼不使用CSS圖像的寬度和高度? – 2010-08-21 10:28:33

+0

它只是一個複製粘貼。 無關 – Tombigel 2010-08-21 11:48:02

回答

0

這裏是我的優化版本...

HTML

<!-- "section" is not valid HTML --> 
<div id="carousel"> 
     <img src="images/01.jpg" width="202" height="162" /> 
</div> 

CSS

/* Same as before */ 
#carousel{text-align:center;position:relative;} 
#carousel img{top:0;left:0;z-index:1;position:absolute;} 

的Javascript

function carousel(el, base, images, i){ 
    //Made the "i" parameter optional 
    if (i == images.length || i == null) i = 0; 
    //Put the variables in a better order 
    var el2 = $(el).clone(); 
    el2.attr('src', base + images[i]); 
    el2.css('z-index', '0'); 
    $(el).css('z-index', '1'); 
    $(el).after(el2); 
    //One line... 
    $(el).fadeOut('slow', function(){$(this).remove();}); 
    i++; 
    //The function doesn't have to be in a variable 
    window.timer = setTimeout(function(){return carousel(el, base, images, i);}, 4000); 
} 

$(function($){ 
    //Didn't include "i" variable 
    carousel('#carousel img:first', 
      'images/', 
      ['01.jpg', 
       '02.jpg', 
       '03.jpg', 
       '04.jpg']); 
}); 
+0

謝謝,但除了刪除「我」你什麼都沒有優化。 – Tombigel 2010-08-23 06:30:55

+0

嗯,這是我可以做的最好的,我認爲它的優化,因爲它可以得到 – 2010-08-23 17:08:58