2

我有这部分代码,旨在每次单击时更改输入按钮的颜色。

function colorchange(id) 
 {
   if(document.getElementById(id).style.background == '#FFFFFF')
  {
   document.getElementById(id).style.background = '#000000';
  }
 else
  {
   document.getElementById(id).style.background = '#FFFFFF';
  }
 }

<input type="button" id="k777" onclick="colorchange('k777');" style="background:#000000;"/>

但是,这不能正常工作。当我第一次单击它时,它确实将按钮的颜色从#000000 更改为#FFFFFF,但是当我再次单击它时,它不会变回#000000。它仍然是白色的。我该如何解决?

4

3 回答 3

4

那是因为element.style.background返回rgb格式的值。更改条件if语句以检查适当的rgb值,它应该可以正常工作。

使该行如下:

if(document.getElementById(id).style.background !== 'rgb(0, 0, 0)')

演示,您的代码已修复和清理

于 2012-08-20T13:27:03.723 回答
1

尝试通过 css-classes 解决它

这里的HTML:

<style type="text/css">
    input.bg_1{
        background-color: #000";
    }
    input.bg_2{
        background-color: #fff;
    }
</style>
<input type="button" id="input_777" onclick="colorchange('input_777');" class="bg_1" value="hello world" />

JS:

function colorchange(id){
    var item = document.getElementById(id);
    if(item.getAttribute('className') == 'bg_1'){
        item.setAttribute('className', 'bg_2');
    } else {
        item.setAttribute('className', 'bg_1');
    }
}

也许属性class在某些浏览器中。你将不得不检查这一点。顺便提一句。代码未经测试

于 2012-08-20T13:42:46.473 回答
0
function colorchange(id) 
 {

     var background = document.getElementById(id).style.background;

     if(background === "rgb(255,255,255)")
     {
     document.getElementById(id).style.background = "rgb(0,0,0)";
     }
     else
     {
        document.getElementById(id).style.background = "rgb(255,255,255)"; 
     }

 }

因为它的 RGB 值,

它在这里工作http://jsfiddle.net/nE8SW/ ​</p>

于 2012-08-20T13:29:51.817 回答