Can I do this with the :hover pseudo class?

非 Y 不嫁゛ 提交于 2019-12-24 04:35:13

问题


I'm familiar with the :hover psuedo class and using it for elements as well as the typical link setup we're all used to. What I am trying to do however is create a situation where hover over one element would change properties of another. For instance if I were to hover over .block1, #block2 would become visible. I would think the .css would look like something this...

.block1:hover div#block2
{
    visibility:visible;
}

but that's getting me nowhere. Thoughts? I know that I could probably use javascript to make this happen (make elements appear and disappear) but I would love to find a pure css solution to this.


回答1:


The element you want to change has to be a child element of the one you are hovering over.

Example CSS:

#navButton div.text {
    display:none;
}

#navButton:hover div.text {
    display:block;
}

This will make the text div display if you hover over the element with id="navButton".

Otherwise, use a JQuery solution:

CSS:

#navButton div.text {
    display:none;
}

.hover {
    display:block;
}

Javascript:

$("#navButton").hover(
    function () {
        $("#navButton div.text").addClass("hover");
    },
    function () {
        $("#navButton div.text").removeClass("hover");
    }
);

Edit:

You can also do this for sibling elements in CSS if the hovered element precedes the element you want to modify. Like so:

#navButton + div.text {
    display:none;
}

#navButton:hover + div.text {
    display:block;
}

OR

#navButton ~ div.text {
    display:none;
}

#navButton:hover ~ div.text {
    display:block;
}



回答2:


If that second element is a descendent of the first, then it will work.

jsFiddle.



来源:https://stackoverflow.com/questions/6353397/can-i-do-this-with-the-hover-pseudo-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!