这里简单记录一下,方便以后查阅
<style>
ul>li {
width: 100%;
height: 30px;
margin-top: 10px;
background-color: blue;
}
.active {
background-color: #ffcd42;
}
</style>
</head>
<body>
<ul id="ul">
<li class="active"></li>
<li></li>
</ul>
<button id="add">添加li标签</button>
</body>
<script>
window.onload = function () {
//按钮添加li标签
document.getElementById('add').onclick = function () {
let li = document.createElement('li');
document.getElementById('ul').appendChild(li);
}
//给li标签注册鼠标经过事件
//这样注册的事件通过后面按钮添加的li元素无法改变颜色
//因为是事件注册的时候还没有该元素
let liList = document.getElementsByTagName('li');
for (let i = 0; i < liList.length; i++) {
liList[i].onmouseover = function (e) {
e = e || window.event;
this.className ? this.className = "":this.className = "active"
}
}
//给ul注册委托事件,可以达到给后面添加的li添加事件的效果
//实现的机制:事件冒泡
document.getElementById('ul').onmouseover = function (e) {
e = e || window.event;
if (e.target.nodeName == 'LI') {
e.target.className ? e.target.className = "":e.target.className = "active"
}
}
}
</script>