要使用JavaScript关闭列表项,代码如下-
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } * { box-sizing: border-box; } ul { list-style-type: none; padding: 0; margin: 0; } ul li { border: 1px solid rgb(221, 221, 221); background-color: #5a5cec; color: white; padding: 12px; text-decoration: none; font-size: 18px; display: block; position: relative; font-weight: 500; } ul li:hover { background-color: rgb(43, 0, 145); } .close { cursor: pointer; position: absolute; top: 50%; right: 0%; padding: 12px 16px; transform: translate(0%, -50%); } .close:hover { background: red; } </style> </head> <body> <h1>Closable List Items Example</h1> <h2>Click 'x' on the list items to close them</h2> <ul> <li>Cat<span class="close">×</span></li> <li>Lion<span class="close">×</span></li> <li>Tiger<span class="close">×</span></li> <li>Leopard<span class="close">×</span></li> <li>Cheetah<span class="close">×</span></li> </ul> <script> var closebtns = document.querySelectorAll(".close"); Array.from(closebtns).forEach(item => { item.addEventListener("click", () => { item.parentElement.style.display = "none"; }); }); </script> </body> </html>
输出结果
上面的代码将产生以下输出-
在某些项目上点击“ x”时-