如何让我的 JS 函数忽略 ID CSS 而只看类?

  • 本文关键字:CSS ID 函数 JS javascript html css
  • 更新时间 :
  • 英文 :


下面的代码工作正常:

filterSelection("all")
function filterSelection(c) {
var x, i;
x = document.getElementsByClassName("filterDiv");
if (c == "all") c = "";
// Add the "show" class (display:block) to the filtered elements, and remove the "show" class from the elements that are not selected
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";
});
}
.container {
overflow: hidden;
}

.filterDiv {
float: left;
background-color: #2196F3;
color: #ffffff;
width: 100px;
line-height: 100px;
text-align: center;
margin: 2px;
display: none;
}

.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;
}
<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>
</div>

<div class="container">
<div class="filterDiv cars">BMW</div>
<div class="filterDiv cars">Volvo</div>
<div class="filterDiv animals">Cat</div>
<div class="filterDiv animals">Dog</div>
</div>


但是如果我更改其中一个div,例如

<div class="filterDiv animals">Dog</div>

<div class="filterDiv animals" id="othercss_unrelated_to_function" >Dog</div>

它完全破坏了该功能。我怎样才能让它优先考虑类 CSS?

我想让函数围绕 ID CSS 工作。有没有一种方法可以将它们排序到层次结构中,这样它们就不会干扰我的 JavaScript?

Id 的优先级为 100。 类的优先级为 10。

因此,无论 ID 在代码中的位置如何,它们都将始终优先于类。

诀窍是在 CSS 中组合一个 ID 和一个类,它的优先级为 110:

#othercss_unrelated_to_function.filterDiv {...}

最新更新