I want that part 1
onclick div style changes and part 2
again on click it comes back to normal. I tried doing so but I failed to achieve the part 2
results.
Following is the Javascript code
function abc() {
document.getElementById("test").style.color="red";
}
After clicking the test div again, color should come back to defaulr color ie black...
function abc() {
var color = document.getElementById("test").style.color;
if (color === "red")
document.getElementById("test").style.color="black";
else
document.getElementById("test").style.color="red";
}
Using jQuery:
$(document).ready(function(){
$('div').click(function(){
$(this).toggleClass('clicked');
});
});
Have some logic to check the color or have some flag,
function abc() {
var currentColor = document.getElementById("test").style.color;
if(currentColor == 'red'){
document.getElementById("test").style.color="black";
}else{
document.getElementById("test").style.color="red";
}
}
function abc() {
var color = document.getElementById("test").style.color;
color = (color=="red") ? "black" : "red" ;
document.getElementById("test").style.color= color;
}
you may check the color before you click to change it.
function abc(){
var color = document.getElementById("test").style.color;
if(color==''){
//change
}else{
//change back
}
}
A simple switch statement should do the trick:
function abc() {
var elem=document.getElementById('test'),color;
switch(elem.style.color) {
case('red'):
color='black';
break;
case('black'):
default:
color='red';
}
elem.style.color=color;
}
Better change the class of the element (.regular is black, .alert is red):
function abc(){
var myDiv = document.getElementById("test");
if (myDiv.className == 'alert') {
myDiv.className = 'regular';
} else {
myDiv.className = 'alert';
}
}
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.