目录

如何操作 - 可关闭列表项


了解如何使用 JavaScript 关闭列表项。


可关闭列表项

单击列表项右侧的 "x" 符号可将其关闭/隐藏。

亲自试一试 »


如何创建可关闭列表项

步骤1)添加HTML:

示例

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

步骤2)添加CSS:

示例

* {
  box-sizing: border-box;
}

/* Style the list (remove margins and bullets, etc) */
ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

/* Style the list items */
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;
}

/* Add a light grey background color on hover */
ul li:hover {
  background-color: #eee;
}

/* Style the close button (span) */
.close {
  cursor: pointer;
  position: absolute;
  top: 50%;
  right: 0%;
  padding: 12px 16px;
  transform: translate(0%, -50%);
}

.close:hover {background: #bbb;}


步骤 3) 添加 JavaScript:

示例

// Get all elements with class="close"
var closebtns = document.getElementsByClassName("close");
var i;

// Loop through the elements, and hide the parent, when clicked on
for (i = 0; i < closebtns.length; i++) {
  closebtns[i].addEventListener("click", function() {
    this.parentElement.style.display = 'none';
  });
}
亲自试一试 »