Hover on element and highlight all elements with the same class

后端 未结 2 1934
夕颜
夕颜 2020-12-09 04:06

I have many elements with the same class on a web page. I would like to highlight all these elements when I hover one of them. How can I do that in CSS?

Right now, I

2条回答
  •  有刺的猬
    2020-12-09 04:33

    The best you can do using pure CSS is this:

    .classname:hover ~ .classname {
        background-color: yellow;
    }
    

    But this only highlights all siblings with a class classname after the hovered element.

    You have to use JavaScript to highlight all elements;

    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");
        };
    }
    

    If you have multiple classes and want to generalize this, use something like this:

    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");
            };
        }
    };
    

提交回复
热议问题