javascript - 如何让事件侦听器使用 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);
解决方案
您的问题是未设置项目背景颜色的初始值。项目 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>
推荐阅读
- f# - F# 或 C# | 如何测试是否调用了扩展方法?
- javascript - ng-click 和 md-button 冲突
- python - 如何解释 python3 的帮助输出?
- vue.js - Vuex 状态由操作更新,但计算属性没有响应
- google-app-maker - Appmaker 获取服务器端模型的所有记录
- c - 我知道这个程序的答案,但我不明白为什么?
- javascript - 如何通过按键使数组递增
- swift - RxSwift 链接:在 Rxswift 中写这个更好的方法是什么?
- java - Flash 属性不适用于 https - 适用于 http
- c - Execvp 与“ls -l | wc”一起工作,但与“ls -l | wc”一起失败