I need to have serval buttons on this web page to change the
color and background color. Here are the actual text and CSS file plus the 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()" ;>
right now I can only change the text color by typing the actually class such as "colorA" and "backgroundB" after I get the element by Id to change the color. but what I am trying to do is in the javascript function, how can I change the text color based on which button I click. What I mean is after I get the element by Id such as "foreground", how can I change its current class (colorB) to the class (colorA) if I just clicked button A
Pass the class name to the function
and use it
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')";>
Try this:
function changeForeground()
{
var div = document.getElementById("foreground").style.color = "#4581cf";
}
function changeBackground()
{
var div = document.getElementById("background").style.backgroundColor = "#B7E2FF";
}
Try this with jquery
function changeForeground()
{var div = $(#foreground).css('color' :'#4581cf');}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.