Highlight all elements with same class when one of them is moused over

前端 未结 3 438
栀梦
栀梦 2021-01-21 13:40

In JavaScript, is it possible to highlight all items with the same class when one of them is moused over?

For example, if I had two paragraphs with the class p1

3条回答
  •  太阳男子
    2021-01-21 14:08

    Here's a working example (which requires JQuery). When a member of p1 is moused over, all other elements of p1 will be highlighted as well. The same is true of p2.

    JavaScript:

    function highlightAllOnMouseover(className){
        $(className).mouseover(function() {
      $(className).css("opacity", 0.4); 
      $(className).css("opacity", 1);
    }).mouseleave(function() { 
        $(className).css("opacity", 0.4);
    });
    }
    highlightAllOnMouseover(".thing1");
    highlightAllOnMouseover(".thing2");
    

    HTML:

    This is thing1.

    This is thing2.

    This is also thing1.

    This is also thing2.

    To cause all elements with a specific class to be highlighted on mouseover, you only need to call the function highlightAllOnMouseover(className), which I created here.

提交回复
热议问题