2012-12-17 25 views
0

所以它的預加載圖像需要從隨機圖像改變jQuery的測序

var headerImages = [ 
     'images/logoa.png', 
     'images/logob.png', 
     'images/logoc.png', 
     'images/logod.png', 
     'images/logoe.png', 
     'images/logog.png', 
     'images/logoh.png', 
     /* 'images/logoi.png', */ 
     'images/test/logoa.png', 
     'images/test/logob.png']; 

,然後挑選在每個頁面滾動,我怎麼讓它在序列中的隨機一個,這意味着從頂至底預加載?

.... 

jQuery.preLoadImages(headerImages); 


jQuery(window).scroll(function() { 
    jQuery('#sidebar').css('backgroundImage', 'url(' + 
headerImages[Math.floor(Math.random()*headerImages.length)] + ')'); 
}); 

所以我想這是這部分Math.floor(Math.random()*headerImages.length),但我不知道該怎麼做..

非常感謝您的幫助!

+0

我忘了,包括預加載功能,只是想知道如果這有什麼差別 –

+0

(功能jQuery.preLoadImages = function(){ if(typeof arguments [0] =='object'){ var {varchar = new_args = []; for(var i = arguments [0] .length; i--;){ new_args.push(arguments [0] [i]); } arguments = new_args; } var args_len = arguments.length;對於(var i = args_len; i--;){ var cacheImage = document.createElement('img'); cacheImage.src = arguments [i]; cache.push(cacheImage); } } })(jQuery) –

+0

沒有預加載函數在這裏沒有任何區別,如果你只想去除圖像的隨機順序 –

回答

1

您可以通過將當前圖像索引存儲在變量中,並在每次滾動時添加。然後當它到達列表的末尾設置爲零:(!並且非常感謝您的快速回復)

jQuery.preLoadImages(headerImages); 

    var index = 0; // set the variable 

    jQuery(window).scroll(function() { 
    jQuery('#sidebar').css('backgroundImage', 'url(' + headerImages[index] + ')'); 

    index ++; // add one to point to the next image on the next scroll 

    if(index==headerImages.length) index = 0; // If the counter is at the end of the array then set it to zero again 

}); 
+0

感謝您的詳細解釋! –

1
var x =0; 
jQuery(window).scroll(function() { 
    jQuery('#sidebar').css('backgroundImage', 'url(' + 
headerImages[x] + ')'); 
x++ 
if (x == headerImages.length) 
{ 
x =0; 
} 
}); 
+0

工作謝謝! –

1

headerImages似乎是一個數組,所以如果你從0到headerImages.lenght做一個循環,你應該罰款,並做一些事情,如:

jQuery('#sidebar').css('backgroundImage', 'url(' + headerImages[x] + ')'); 

在循環中,其中x是變量你從0增加到最大值。