如何创建 - 过滤元素
了解如何根据类名过滤 DIV 元素。
过滤 DIV 元素
BMW
Orange
Volvo
Red
Mustang
Blue
Cat
Dog
Melon
Kiwi
Banana
Lemon
Cow
创建可过滤的 DIV 元素
步骤 1) 添加 HTML:
实例
<!-- 控制按钮 -->
<div id="myBtnContainer">
<button
class="btn active" onclick="filterSelection('all')"> Show all</button>
<button class="btn" onclick="filterSelection('cars')"> Cars</button>
<button class="btn" onclick="filterSelection('animals')"> Animals</button>
<button class="btn" onclick="filterSelection('fruits')"> Fruits</button>
<button class="btn" onclick="filterSelection('colors')"> Colors</button>
</div>
<!-- 可过滤的元素。 请注意,有些有多个类名(如果它们属于多个类别,则可以使用此名称) -->
<div
class="container">
<div
class="filterDiv cars">BMW</div>
<div class="filterDiv colors
fruits">Orange</div>
<div class="filterDiv cars">Volvo</div>
<div class="filterDiv colors">Red</div>
<div class="filterDiv cars
animals">Mustang</div>
<div class="filterDiv colors">Blue</div>
<div class="filterDiv animals">Cat</div>
<div class="filterDiv
animals">Dog</div>
<div class="filterDiv fruits">Melon</div>
<div class="filterDiv fruits animals">Kiwi</div>
<div class="filterDiv
fruits">Banana</div>
<div class="filterDiv fruits">Lemon</div>
<div class="filterDiv animals">Cow</div>
</div>
步骤 2) 添加 CSS:
实例
.container {
overflow: hidden;
}
.filterDiv {
float: left;
background-color: #2196F3;
color: #ffffff;
width: 100px;
line-height: 100px;
text-align: center;
margin: 2px;
display: none;
/* 默认隐藏 */
}
/* "show" 类被添加到过滤后的元素中 */
.show {
display: block;
}
/* 为按钮设置样式 */
.btn {
border: none;
outline: none;
padding: 12px 16px;
background-color:
#f1f1f1;
cursor: pointer;
}
/* 在鼠标悬停时添加浅灰色背景 */
.btn:hover {
background-color: #ddd;
}
/* 为活动按钮添加深色背景 */
.btn.active {
background-color: #666;
color: white;
}
步骤 3) 添加 JavaScript:
实例
filterSelection("all")
function filterSelection(c) {
var x, i;
x = document.getElementsByClassName("filterDiv");
if (c == "all") c = "";
// 过滤后的元素添加 "show" 类(display:block),未选中的元素移除 "show" 类
for (i = 0; i < x.length; i++) {
w3RemoveClass(x[i],
"show");
if (x[i].className.indexOf(c) > -1)
w3AddClass(x[i], "show");
}
}
// 显示过滤后的元素
function w3AddClass(element, name) {
var i, arr1, arr2;
arr1 = element.className.split("
");
arr2 = name.split(" ");
for (i = 0; i < arr2.length;
i++) {
if (arr1.indexOf(arr2[i]) == -1) {
element.className += " " + arr2[i];
}
}
}
// 隐藏未选中的元素
function w3RemoveClass(element, name) {
var i, arr1, arr2;
arr1 = element.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);
}
}
element.className = arr1.join(" ");
}
// 将活动类添加到当前控制按钮(突出显示)
var btnContainer = document.getElementById("myBtnContainer");
var btns =
btnContainer.getElementsByClassName("btn");
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";
});
}
亲自试一试 »