如何根据CSS和JavaScript的类名称过滤DIV元素?
要根据类名称过滤DIV元素,代码如下-
示例
<!DOCTYPE html> <html> <style> .filterElements { float: left; font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; font-size: 20px; background-color: rgb(28, 98, 179); color: #ffffff; width: 100px; line-height: 100px; text-align: center; margin: 2px; display: none; } .show { display: block; } .container { margin-top: 20px; overflow: hidden; } .btn { border: none; font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; font-size: 14px; outline: none; padding: 12px 16px; background-color: #d6e5ec; cursor: pointer; } .btn:hover { background-color: rgb(157, 209, 211); } .btn.active { background-color: rgb(34, 95, 228); color: white; } </style> <body> <h1>Filter DIV Elements Example</h1> <div class="filterBtns"> <button class="btn active" onclick="filterSelection('all')">Show all</button> <button class="btn" onclick="filterSelection('animals')">Animals</button> <button class="btn" onclick="filterSelection('fruits')">Fruits</button> </div> <div class="container"> <div class="filterElements fruits">Orange</div> <div class="filterElements animals">Giraffe</div> <div class="filterElements animals">Cheetah</div> <div class="filterElements animals">Lion</div> <div class="filterElements fruits">Guava</div> <div class="filterElements animals">Dog</div> <div class="filterElements fruits">Banana</div> <div class="filterElements fruits">Mango</div> <div class="filterElements animals">Bull</div> </div> <script> filterSelection("all"); function filterSelection(c) { var x, i; x = document.querySelectorAll(".filterElements"); if (c == "all") c = ""; Array.from(x).forEach(item => { removeActiveClass(item, "show"); if (item.className.indexOf(c) > -1) addActiveClass(item, "show"); }); } function addActiveClass(ele, name) { var i, arr1, arr2; arr1 = ele.className.split(" "); arr2 = name.split(" "); for (i = 0; i < arr2.length; i++) { if (arr1.indexOf(arr2[i]) == -1) { ele.className += " " + arr2[i]; } } } function removeActiveClass(ele, name) { var i, arr1, arr2; arr1 = ele.className.split(" "); arr2 = name.split(" "); for (i = 0; i < arr2.length; i++) { while (arr1.indexOf(arr2[i]) > -1) { arr1.splice(arr1.indexOf(arr2[i]), 1); } } ele.className = arr1.join(" "); } var filterBtns = document.querySelector(".filterBtns"); var btns = filterBtns.getElementsByTagName("button"); for (var i = 0; i < btns.length; i++) { btns[i].addEventListener("click", function() { var current = document.getElementsByClassName("active"); current[0].className = current[0].className.replace(" active", ""); this.className += " active"; }); } </script> </body> </html>
输出结果
上面的代码将产生以下输出-
单击任何过滤器按钮时-