以下实例我们演示了如何使用 JavaScript 来关闭列表选项:
<ul>
<li>Adele</li>
<li>Agnes<span class="close">x</span></li>
<li>Billy<span class="close">x</span></li>
<li>Bob<span class="close">x</span></li>
<li>Calvin<span class="close">x</span></li>
<li>Christina<span class="close">x</span></li>
<li>Cindy</li>
</ul>
* {
box-sizing: border-box;
}
/* 列表 */
ul {
list-style-type: none;
padding: 0;
margin: 0;
}
/* 列表选项样式 */
ul li {
border: 1px solid #ddd;
margin-top: -1px; /* Prevent double borders */
background-color: #f6f6f6;
padding: 12px;
text-decoration: none;
font-size: 18px;
color: black;
display: block;
position: relative;
}
/* 鼠标移动过去后添加灰色背景 */
ul li:hover {
background-color: #eee;
}
/* 设置关闭按钮 */
.close {
cursor: pointer;
position: absolute;
top: 50%;
right: 0%;
padding: 12px 16px;
transform: translate(0%, -50%);
}
.close:hover {background: #bbb;}
/* 获得 class="close" 的所有元素 */
var closebtns = document.getElementsByClassName("close");
var i;
/* 循环元素,在点击时关闭它 */
for (i = 0; i < closebtns.length; i++) {
closebtns[i].addEventListener("click", function() {
this.parentElement.style.display = 'none';
});
}