2011-09-23 111 views
0

我有以下腳本:如何改變基於javascript變量值的元素類?

<script> 
    window.now = some_int_value; 
</script> 

和下面的HTML:

<span class="dot"></span>&nbsp; 
<span class="dot active"></span>&nbsp; 
<span class="dot"></span>&nbsp; 
<span class="dot"></span>&nbsp; 

我應該如何改變按照點的風格window.now價值?所以,如果它等於1,那麼第一個點應該是'dot active',如果等於2,那麼等於2。

回答

1
document.getElementsByClassName("dot")[window.now-1].className += " active"; 

你可以做到這一點(對於IE9 +和所有其他主流瀏覽器)。

或者你可以使用

document.querySelectorAll(".dot")[window.now-1].className += " active"; 

爲IE8 +,FF3 +,和所有其他的主流瀏覽器。

,或者你可以通過任何機會,應該是一個4點的進度條/活動指示器將它們結合起來

if(document.getElementsByClassName); 
    document.getElementsByClassName("dot")[window.now-1].className += " active"; 
else if(document.querySelectorAll) 
    document.querySelectorAll(".dot")[window.now-1].className += " active"; 

Compatibility Documentation

+1

getElementsByClassName未在IE 7中實現並且(I相信在IE8中也是如此) –

+0

嗯,可能我應該爲每個點分配id? –

+0

@JohnHartsock感謝您的信息:)我已經更新了我的答案。 –

0

這不,?如果是這樣,我會說只是使用一個gif - 有一個網站,可以爲你生成它們:http://preloaders.net/

+0

不,它不是進度條 - 它會顯示活動頁面(就像在主iphone屏幕上一樣)。 –

1

你應該考慮看看jQuery,它簡化了DOM的工作。

這是所有你需要在jQuery的你的指標:

$('span.dot').eq(window.now - 1).addClass('active'); 

沒有更多

  • 「也許我應該分配一個ID給每個點」
  • 「 getElementByTagName()不是在一些或多或少模糊的瀏覽器「」中實現的。
  • 「這不會在IE8工作」
  • ...
0

這應做到:

var dots = document.querySelectorAll('.dot'); 

[].slice.call(dots).forEach(function (dot, i) { 
    dot.className = 'dot' + (window.now === i + 1 ? ' active' : ''); 
}); 

(這並不在IE8工作。)

現場演示:http://jsfiddle.net/dKDLx/

(該演示顯示即使2. dot類設置爲「active」,window.now = 3;將導致該類被「移動」到3. dot。)