2015-09-03 17 views
1

我有18張圖像,我只希望在任何給定時間顯示5個圖像。我每兩秒鐘換出一幅新圖像而不顯示重複內容。我的HTML是硬編碼並從s3桶中提取。遞增計數器然後在達到一定限制時重置該計數器

<img class="activeImg" src="img_1.jpg /> 
<img src="img_2.jpg /> 
<img src="img_3.jpg /> 
<img src="img_4.jpg /> 
... 
<img src="img_9.jpg /> 

我有一個遞歸函數setTimeout正在調用moveCountermoveCounter只需增加1,並在每次調用時都會替換圖像。我將activeImg類添加到img中,然後在移到下一個圖像之前將其刪除。

最終目標是從0 ... 5開始計數,然後無限地回落到5 ... 0。我所做的只是將值附加到圖像名稱,從而替換圖像而不顯示重複。

問題是有重疊,我得到一個重複每當counter === imgId

// my recursive settimeout function fires off and adds an activeImg class to a random image element, then also fires off the replaceImage function 

var counter = 0; 
var imgId  = 18; 

    // increment counter and append new img 
    function replaceImage(imgId){ 

    if (counter >= 9) { 
     counter--; 
     var imgId = imgId - counter; 
    } else { 
     counter++; 
     var imgId = imgId - counter; 
    } 

    jQuery('.activeImg').attr('src', "image/img_"+imgId+".jpg"); 

    console.debug(counter) 
    console.debug(imgId) 

    } 

我覺得有一個更好的方法來解決這個問題。

回答

2
var counter = 1; 
var imgId = 18; 

var op = 1; // the operation -- 1 for addition, -1 for subtraction 


function replaceImage(imgId) { 
    // increment or decrement the counter, depending 
    // on the current direction 
    counter += op; 

    // use the original poster's snippet to set the active image 
    var imgId0 = imgId + counter; 
    $('.activeImg').attr('src', 'image/img_'+imgId0+'.jpg'); 

    // if we hit the upper or lower bound, reverse the direction 
    // by flipping the operation 
    if (counter === 5 || counter === 1) 
    op *= -1; 
} 
+0

@DavidThomas完成:) – twinlakes

2

看起來你正在尋找的是一個簡單的triangle wave
您可以比較容易地生成一個:

var a = 5; 
 
var output = []; 
 

 
for (var i = 0; i < 20; i++) { 
 
    output.push(a - Math.abs(i % (2 * a) - a)); 
 
}; 
 
out.innerHTML = output;
<span id="out"></span>