开发者问题收集

使用 javascript 更改文本颜色和背景颜色

2017-02-08
3626
function changeForeground() {
  var div = document.getElementById("foreground").className = "colorA";
}

function changeBackground() {
  var div = document.getElementById("background").className = "backgroundB";
}
.colorA {
  color: #4581cf;
}
.colorB {
  color: #B7E2FF;
}
.backgroundA {
  background-color: #4581cf;
}
.backgroundB {
  background-color: #B7E2FF;
}
<div id="background" class="backgroundA">
  <div id="foreground" class="colorB">
    <p>blah blah blah</p>
  </div>
</div>

Foreground
<INPUT type="button" Value="A" class="colorA" id="button1" onclick="changeForeground()" ;>
<INPUT type="button" Value="B" class="colorB" id="button2" onclick="changeForeground()" ;>Background
<INPUT type="button" Value="C" class="backgroundA" id="button3" onclick="changeBackground()" ;>
<INPUT type="button" Value="D" class="backgroundB" id="button4" onclick="changeBackground()" ;>
3个回答

将类名传递给 函数 并使用它

function changeForeground(cls){
  var div = document.getElementById("foreground").className=cls;
}
                                        
function changeBackground(cls){
  var div = document.getElementById("background").className=cls;
}
.colorA{
      color: #4581cf;
    }

    .colorB{
      color: #B7E2FF;
    }

    .backgroundA{
      background-color: #4581cf;
    }

    .backgroundB{
      background-color: #B7E2FF;
    }
<div id="background" class="backgroundA">
   <div id="foreground" class="colorB">
        <p>blah blah blah</p>
   </div>
</div>

Foreground 
    <INPUT type="button" Value="A" class="colorA" id="button1" onclick ="changeForeground('colorA')";>
    <INPUT type="button" Value="B" class="colorB" id="button2" onclick ="changeForeground('colorB')";>

Background
    <INPUT type="button" Value="C" class="backgroundA" id="button3" onclick ="changeBackground('backgroundA')";>
    <INPUT type="button" Value="D" class="backgroundB" id="button4" onclick ="changeBackground('backgroundB')";>
Suren Srapyan
2017-02-08

尝试一下:

function changeForeground()
{
    var div = document.getElementById("foreground").style.color = "#4581cf";
}

function changeBackground()
{
    var div =    document.getElementById("background").style.backgroundColor = "#B7E2FF";
}  
Kishore Krishnan
2017-02-08

使用 jquery 尝试一下

     function changeForeground()
        {var div = $(#foreground).css('color' :'#4581cf');}
Wassim Ben Hssen
2017-02-08