使用纯 CSS 可以做到的最好的事情是:
.classname:hover ~ .classname {
background-color: yellow;
}
但这只会在悬停元素classname
之后突出显示所有具有类的兄弟姐妹。
您必须使用 JavaScript 突出显示所有元素;
var elms = document.getElementsByClassName("classname");
var n = elms.length;
function changeColor(color) {
for(var i = 0; i < n; i ++) {
elms[i].style.backgroundColor = color;
}
}
for(var i = 0; i < n; i ++) {
elms[i].onmouseover = function() {
changeColor("yellow");
};
elms[i].onmouseout = function() {
changeColor("white");
};
}
如果您有多个类并想要概括这一点,请使用以下内容:
var classes = ["one", "two", "three"]; //list of your classes
var elms = {};
var n = {}, nclasses = classes.length;
function changeColor(classname, color) {
var curN = n[classname];
for(var i = 0; i < curN; i ++) {
elms[classname][i].style.backgroundColor = color;
}
}
for(var k = 0; k < nclasses; k ++) {
var curClass = classes[k];
elms[curClass] = document.getElementsByClassName(curClass);
n[curClass] = elms[curClass].length;
var curN = n[curClass];
for(var i = 0; i < curN; i ++) {
elms[curClass][i].onmouseover = function() {
changeColor(this.className, "yellow");
};
elms[curClass][i].onmouseout = function() {
changeColor(this.className, "white");
};
}
};