如何使用 CSS 显示和隐藏 div?

2022-01-22 00:00:00 hover siblings html css

在我的脚本中有三个 div.当我将鼠标悬停在第一行时,我想用 class="ab" 显示 div,当悬停在第二行时,我想用 class="abc" 显示 div.否则我想默认显示带有 class="a" 的 div.

In my script there are three divs. I want to display div with class="ab" when I hover on first line and display div with class="abc", when hover on second line. Otherwise I want to display div with class="a" by default.

但它从不显示带有 class="a" 的 div.

But it never displays the div with class="a".

.abc,.ab {
    display: none;
}
#f:hover ~ .ab {
    display: block;

}
#f:hover ~ .abc,.a {
    display: none;

}
#s:hover ~ .abc {
    display: block;

}
#s:hover ~ .ab,.a {
    display: none;
}

<a id="f">Show First content!</a>
<br/>
<a id="s">Show Second content!!</a>
<div class="a">Default Content</div>
<div class="ab">First content</div>
<div class="abc">Second content</div>

这是我的问题的 JSFiddle:JSFiddle 链接

Here is my JSFiddle of my problem: JSFiddle Link

推荐答案

你需要

.abc,.ab {
    display: none;
}

#f:hover ~ .ab {
    display: block;
}

#s:hover ~ .abc {
    display: block;
}

#s:hover ~ .a,
#f:hover ~ .a{
    display: none;
}

在 http://jsfiddle.net/gaby/n5fzB 处更新了演示/2/

原始 CSS 中的问题是 css 选择器中的 , 启动了一个全新的选择器.它没有合并.. 所以 #f:hover ~ .abc,.a 表示 #f:hover ~ .abc.a.您将其设置为 display:none 因此它始终设置为对所有 .a 元素隐藏.

The problem in your original CSS was that the , in css selectors starts a completely new selector. it is not combined.. so #f:hover ~ .abc,.a means #f:hover ~ .abc and .a. You set that to display:none so it was always set to be hidden for all .a elements.

相关文章