切换按钮的背景颜色

Toggling the background color of buttons

本文关键字:背景 颜色 按钮      更新时间:2023-09-26

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

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。它还是白色的。我该如何解决这个问题?

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

把这行写成:

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

演示,修复并清理代码的

尝试通过css类解决它

这里的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。你必须检查一下。顺便说一句,代码未经测试

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/​