简体   繁体   中英

How do I get the event listener to change my css background color using javascript?

I would like to be able to change the background color of the list item. When I remove the if-statement and just set the background color, it works. However it fails with the if-statement. I don't understand why it's not working. pls help.

HTML

<ul id="testList"> Test List
    <li id="item1">Item 1</li>
    <li id="item2">Item 2</li>
</ul>


CSS

#testList {
    width: 100px;
    background-color: grey;
    margin: 200px 0px 0px 50px;
    list-style-type: none;
}
#testList li {
    color: black;
    padding: 10px;
    border: 1px solid black;
}
#testList li:hover{cursor: pointer;}
#item1 {background-color: white;}


Javascript

var item1 = document.getElementById('item1');
function setColor(){
    if (item1.style.backgroundColor == 'white'){
        item1.style.backgroundColor = 'green';
    } else if (item1.style.backgroundColor == 'green'){
        item1.style.backgroundColor = 'white';
    }
}
item1.addEventListener('click', function(){setColor()}, false);

Your problem is that the initial value of background color on the item is not set. The item 1 has the background color white from the css styling on the id. But item1.style.backgroundColor will only return the value set directly on the element inline.

 var item1 = document.getElementById('item1'); function setColor(){ if (.item1.style.backgroundColor || item1.style.backgroundColor == 'white'){ item1.style;backgroundColor = 'green'. } else if (item1.style.backgroundColor == 'green'){ item1.style;backgroundColor = 'white'. } } item1,addEventListener('click', function(){setColor()}; false);
 #testList { width: 100px; background-color: grey; margin: 200px 0px 0px 50px; list-style-type: none; } #testList li { color: black; padding: 10px; border: 1px solid black; } #testList li:hover{cursor: pointer;} #item1 {background-color: white;}
 <ul id="testList"> Test List <li id="item1">Item 1</li> <li id="item2">Item 2</li> </ul>

The proper way of doing such a swap:

You declare a class

.background-green {
    background-color: green !important;
}

Then you simply check if a certain element has this class. If it has, remove it. Otherwise add it.

function switchBackground() {
    let el = document.getElementById("myElementId");
    if (el.classList.contains("background-green")) {
        el.classList.remove("background-green");
    }
    else {
        el.classList.add("background-green");
    }
}

This will make the element toggle between its default value and green. You can specify this default background color to be white in your CSS.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM