Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

javascript - Use :hover to modify the css of another class?

Is there a way to modify the css for one class when hovering on an element from another class using only css ?

Something like:

.item:hover .wrapper { /*some css*/ }

Only 'wrapper' is not inside 'item', it's somewhere else.

I really don't want to use javascript for something this simple, but if I have to, how would I do it ? Here's my failed attempt:

document.getElementsByClassName('item')[0].onmouseover="document.getElementsByClassName('wrapper')[0].style.background="url('some url')";";

There's only one element of each class. Don't know why they didn't use IDs when they made the template, but that's just how it is and I can't change it.

[Edit]

It's a menu. Each menu element has a distinct class. When you hover on the element a submenu pops up to the right. It's like an overlay, when I use the 'Inspect Element' tool I can see that the whole website html changes when the submenu is active(meaning there's nothing but the submenu). The class I call 'wrapper' has the css that controls the background for the submenu. There's really no connection that I can see between the two classes.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are two approaches you can take, to have a hovered element affect (E) another element (F):

  1. F is a child-element of E, or
  2. F is a later-sibling (or sibling's descendant) element of E (in that E appears in the mark-up/DOM before F):

To illustrate the first of these options (F as a descendant/child of E):

.item:hover .wrapper {
    color: #fff;
    background-color: #000;
}?

To demonstrate the second option, F being a sibling element of E:

.item:hover ~ .wrapper {
    color: #fff;
    background-color: #000;
}?

In this example, if .wrapper was an immediate sibling of .item (with no other elements between the two) you could also use .item:hover + .wrapper.

JS Fiddle demonstration.

References:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...