How to target all divs of the same class except for hovered over div?

前端 未结 3 668
野的像风
野的像风 2021-01-28 09:23

I have a set of divs all with the same class (they don\'t have to have the same class if it makes this easier). Ideally what I want is when a user hovers over one of these divs

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-28 10:01

    There isn't a sibling combinator that lets you select all other siblings of another element. Atomically you would represent this with .box:not(:hover) as shown in other answers, but you can't select all other .box:not(:hover) elements relatively to a .box:hover element in the same parent.

    You could do this partway with the sibling combinators + and ~, but they only look at siblings that follow an element:

    .box:hover ~ .box {
        -webkit-filter: grayscale(100%);
        -moz-filter: grayscale(100%);
        -o-filter: grayscale(100%);
        -ms-filter: grayscale(100%);
        filter: grayscale(100%);
    }
    

    This means if you hover the 2nd box, then only the 3rd and 4th boxes will gray out but not the 1st.

    There isn't a way to select preceding siblings with CSS. Currently the only way to accomplish what you want is to use JavaScript to toggle your styles on the other boxes when hovering a particular box.

提交回复
热议问题