我在寫一組特定的函數時遇到了問題。我正在爲響應式網站設計視覺贊助商欄。我有大約20個贊助商標誌,分爲5個div,我需要隨機循環。如果每個div只有2個圖像,我已經開始使用的代碼無縫工作。輕量級函數使圖像數組隨機循環?
圖像隨機淡入和淡出;然而,我需要的功能不僅僅是一個觸發器效果。簡而言之,我需要爲每個div創建一個旋轉圖像陣列,然後編寫一個函數隨機選擇一個,將該陣列中的任何可見像素都關閉,然後淡入所選圖像。
I我總結了這一點,並發現如果圖像以列表格式進行佈局時可以使用的代碼,但是在響應瀏覽器窗口大小時,我需要圖像浮動和換行。任何幫助(和解釋)將不勝感激。
謝謝!
鏈接到整個小提琴低於,但第(5)申報單是這樣的:
<div class="rotator">
<img src="http://www.fourtownfair.com/images/sponsors/agway.png" class="rotator-image" />
<img src="http://www.fourtownfair.com/images/sponsors/robertrookey.png" class="rotator-image"/>
<img src="http://www.fourtownfair.com/images/sponsors/fairviewfarms.png" class="rotator-image" />
<img src="http://www.fourtownfair.com/images/sponsors/redrobin.png" class="rotator-image" />
</div>
<div class="rotator">
<img src="http://www.fourtownfair.com/images/sponsors/equestriancollection.png" class="rotator-image" />
<img src="http://www.fourtownfair.com/images/sponsors/salmonbrook.png" class="rotator-image" />
<img src="http://www.fourtownfair.com/images/sponsors/smyth.png" class="rotator-image" />
<img src="http://www.fourtownfair.com/images/sponsors/conlinfarm.png" class="rotator-image" />
</div>
的Javascript:
$(function() {
//Timeout are called once and only once, you need to use Interval to repeat the call :-)
$(document).ready(function() {
//Interval with millisecond delay, 2000 = every 2 seconds, always divide by 1000 to get the time.
setInterval(function(){rotateImages();}, 2000);
});
//Breaking this function out, to make the interval statement more readable
var rotateImages = function() {
//Another thing I do to enhance readability, break the collection into a variable
var rotatorArray = $(".rotator");
//We've got the array of rotator blocks, select a random one by length (out of 5 in this case)
var rand = Math.floor(Math.random() * rotatorArray.length);
//If the topmost randomly selected image is hidden, fade in, if it's visible, fade out
if($(rotatorArray[rand].children[0]).css('display') == "none")
{
$(rotatorArray[rand]).children(".rotator-image").fadeIn();
}
else
{
$(rotatorArray[rand]).children(".rotator-image").fadeOut();
}
};
});
小提琴這裏: http://jsfiddle.net/amandabeau/8Y7NM/5/
我們都犯了同樣的錯誤,我們使用Math.round而不是Math.floor。這導致了一個問題,它試圖加載一個圖像,甚至沒有(4圖像索引0,1,2,3,而Math.round可能會返回4) –
@JonasGrumann哎呀,好點! –