Javascript change Div style

2020-03-01 02:53发布

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 i.e. black...

标签: javascript
7条回答
叼着烟拽天下
2楼-- · 2020-03-01 03:12
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";
}
查看更多
闹够了就滚
3楼-- · 2020-03-01 03:15

Using jQuery:

$(document).ready(function(){
    $('div').click(function(){
        $(this).toggleClass('clicked');
    });
});​

Live example

查看更多
Melony?
4楼-- · 2020-03-01 03:22
function abc() {
    var color = document.getElementById("test").style.color;
    color = (color=="red") ? "black" : "red" ;
    document.getElementById("test").style.color= color;
}
查看更多
何必那么认真
5楼-- · 2020-03-01 03:23

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;
}
查看更多
闹够了就滚
6楼-- · 2020-03-01 03:30

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
     }
}
查看更多
贼婆χ
7楼-- · 2020-03-01 03:31

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";

    }
}
查看更多
登录 后发表回答