2013-12-11 18 views
-1

以下是具有3個函數Increment(),Stop(),Start()的簡單JavaScript代碼。手動配置值並在JavaScript中更改方框(圓圈)的顏色

var value = 0; 
var end; 

function Increment(){ 
    value++; 
    document.getElementById('counter').innerHTML = 'Value: ' + value + '<br />';  
} 
end = setInterval(Increment, 1000); 

function Stop(){ 
    clearInterval(end); 
} 

function Start(){ 
    end = setInterval(Increment, 1000); 
} 


<p id="counter"></p></br> 
<div> 
    <input id= "btn1" type="button" value="Stop" onclick="Stop()"> 
    <input id = "btn2" type="button" value="Start Again" onclick="Start()">    
</div> 
  1. 我如何可以手動配置價值;就像我會輸入一個所需的值,它將從該值開始。
  2. 如何設置閾值,超過閾值後,對應的框/圓會改變顏色。

感謝,種類方面,

+0

你知道的'if'說法是什麼?我會從那裏開始。 – epascarello

+0

@epascarello是的,我知道'if'語句。你能告訴我繼續的想法嗎? – royki

+0

所以你比較數字,你想成爲最大。改變你想要的內部if。從文本框中獲取起始號碼或從中獲取值。 – epascarello

回答

0
  1. 如果你的意思是你怎麼會在代碼方面設置的值,那麼只需修改VAR值= 0線,以任何你想要的值。如果您希望用戶能夠設置該值,那麼您將使用輸入來獲取用戶值,然後將其設置爲var value =。

  2. 在腳本中,加入增量的線(),如「如果(值> = _){」與在空白的閾值,然後該支架後添加顏色改變的代碼。

+0

我從用戶那邊問。 – royki

0

您想添加一個允許用戶設置初始值的輸入字段。我也不建議編寫內聯JavaScript - 查看不顯眼的JavaScript主題。

下面是你的startCounting()應該是這樣的:

// Hold our counter info 
var counter = { 
    currValue: 0, 
    interval: null 
}; 

function startCounting() { 
    // Set the current value if provided 
    counter.currValue = startValueField.value || 0; 
    counter.interval = setInterval(increment, 1000); 
} 

我將離開添加閾值作爲練習。這是一樣的想法。

FIDDLE