onclick= 更改表单中同一类的所有输入文本字段背景颜色

onclick= change all input text field background color of the same class in a form

本文关键字:一类 输入 文本 颜色 背景 字段 表单 onclick      更新时间:2023-09-26

让它在IE7中工作。尝试通过类更改表单中输入文本字段的背景颜色。我知道IE7不支持getelementsbyClassName,所以必须创建函数。我已经尝试了很多getelementsbyClassName函数的例子,但没有一个对我有用。希望有人能为我提供解决方案。

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>

这在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;
}

您可以使用styleSheetid而不是 styleSheets[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/