1

使其在IE7中正常工作。 嘗試通過類更改表單中輸入文本字段的背景顏色。 我知道IE7不支持getelementsbyClassName,因此必須創建函數。我已經嘗試了很多getelementsbyClassName函數的例子,但沒有一個適用於我。希望有人能爲我提供一個解決方案。onclick =以一種形式更改同一類的所有輸入文本字段背景顏色

function changecolor() { 
    //i don't know what to put here 
} 

<input type="text" class="items"> 
<input type="text" class="items"> 
<input type="text" class="items"> 
<div onclick="changecolor()">Change Color</div> 
+0

爲什麼不使用jQuery ...... – 2012-04-21 12:31:12

+0

@naimshaikh如果用戶想要的jQuery,他應該標記它 - 但他沒有 – Joseph 2012-04-21 12:32:34

+0

http://robertnyman.com/2008/05/27/the-ultimate-getelementsbyclassname-anno-2008/ – 2012-04-21 12:33:34

回答

1

該做的伎倆在IE7:

function changecolor(c){ 
    var a,n; 
    a=getElementsByTagName('INPUT'); // or a=document.all for all elements in items-class; 
    for(n=0;n<a.length;a++){ 
    if(a[n].className=='items'){ 
    a[n].style.backgroundColor=c; 
    } 
    return; 
} 

您也可以編輯class規則,但它不能保證真正改變顏色,迴流該頁面之前。

function changeColor(c){ 
    var sSheet,n; 
    sSheet=document.styleSheets[0].rules; 
    for(n=0;n<sSheet.length;n++){ 
     if(sSheet[n].selectorText=='.items') sSheet[n].style.backgroundColor=c; 
    } 
    return; 
} 

可以使用styleSheet,而不是指數的idstyleSheets[0]

0

既然你想使用現代功能,但需要支持古代瀏覽器,最好的解決方案是使用庫,如jQuery

使用jQuery你想要做的是超級簡單:

<input type="text" class="items"> 
<input type="text" class="items"> 
<input type="text" class="items"> 
<div id="changeColor">Change Color</div> 

<script> 
$('#changeColor').on('click', function() { 
    $('input.items').css('backgroundColor', '#0ff'); 
}); 
</script> 

這裏有一個演示:http://jsfiddle.net/ThiefMaster/kSwv8/

相關問題