2012-01-21 109 views
1

這是我的代碼,但我想要一個無限循環。請幫助,溫柔。解釋代碼的完整位置,因爲我不知道html。 如果你有一個更好的代碼供我使用,我將不勝感激,但我發現這在網絡上,它的工作原理除了無限循環。 這是一個2圖像幻燈片。無限循環幻燈片

<script type="text/javascript"> 
<!-- 
var image1=new Image() 
image1.src="/v/vspfiles/assets/images/home1.jpg" 

var image2=new Image() 
image2.src="/v/vspfiles/assets/images/home2.jpg" 
//--> 
</script> 


<div style="text-align: left;"><br></div><div style="text-align: center;"><img   src="http://xvrlm.lhcjd.servertrust.com/v/vspfiles/assets/images/home2.jpg" name="slide" width="610" height="78"> 
<script> 
<!-- 

//variable that will increment through the images 
var step=1 
function slideit(){ 

    //if browser does not support the image object, exit. 
    if (!document.images) 
     return 
    document.images.slide.src=eval("image"+step+".src") 
    if (step<3) 
     step++ 
    else 
     step=1 
    //call function "slideit()" every 2.5 seconds 
    setTimeout("slideit()",2500) 
} 
slideit() 

//--> 
</script> 
+0

什麼是document.images.slide? – mowwwalker

+0

我相信你的代碼也運行了無限次... –

回答

1

如果你只有兩頁,那麼你需要確保你的step計數器只穿過值1和2 - 現有的代碼將通過值1,2 3(你確實有一個測試,表示if(step<3)但在之後執行,值3已被使用)。否則,你非常接近。是

var step=1, 
    maxStep = 2; 

function slideit(){ 
    //if browser does not support the image object, exit. 
    if (!document.images) 
     return; 
    document.images.slide.src=eval("image"+step+".src"); 
    if (step<maxStep) 
     step++; 
    else 
     step = 1; 
    //call self again in 2.5 seconds 
    setTimeout(slideit,2500); 
} 
slideit(); 

我做了如下變化:也許是這樣的

  • 固定的if測試,以便它不處理一個以上的圖像比你確實有
  • 添加一個maxStep變量,而不是硬編碼函數內的最大(顯然這是可選的)
  • 添加分號到處都是 - 不,你不能需要他們(爲ST atements在 FUNCTION_),但我更喜歡將它們包括
  • 更新註釋約setTimeout()刪除,它的功能就像setInterval()
  • 更新調用setTimeout()寓意傳遞給函數的引用而不是字符串 - 它可以以任何方式工作,但傳遞函數引用不會丟失範圍(這不是那個問題),並且執行起來更快