我需要在此网页上设置多个按钮来更改
颜色和背景颜色。 这是实际的文本和 CSS 文件以及 javascript
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()" ;>
现在我只能在通过 Id 获取元素更改颜色后,通过键入实际类(例如“colorA”和“backgroundB”)来更改文本颜色。 但我想做的是在 javascript 函数中,如何根据我单击的按钮更改文本颜色。 我的意思是,在我通过 Id 获取元素(例如“foreground”)后,如果我只是单击按钮 A,如何将其当前类(colorB)更改为类(colorA)
最佳答案
将类名传递给函数
并使用它
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')";>
关于javascript - 使用javascript更改文本颜色和背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42106318/