首页 > 解决方案 > 如何让事件侦听器使用 javascript 更改我的 css 背景颜色?

问题描述

我希望能够更改列表项的背景颜色。当我删除 if 语句并设置背景颜色时,它可以工作。但是,它会因 if 语句而失败。我不明白为什么它不起作用。请帮忙。

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

标签: javascripthtmlcss

解决方案


您的问题是未设置项目背景颜色的初始值。项目 1 的背景颜色为白色,来自 id 上的 css 样式。但是 item1.style.backgroundColor 只会返回直接在元素内联上设置的值。

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>


推荐阅读