我要做的是将鼠标悬停在一个元素上并更改CSS中另一个元素的显示。我问了一个关于如何更早地做到这一点的问题,但是,现在我添加了多个元素并且它不起作用。代码如下,我在这里遗漏了什么吗?
CSS
.main-map {
width: 700px;
height: 558px;
float: left;
position: relative;
margin-top: 100px;
background-image: url(map-london.png);
}
.contact-box {
width: 250px;
position: relative;
float: right;
height: 300px;
margin-right: -160px;
margin-top: -50px;
}
#contact1 {
position: absolute;
float: left;
top: 0px;
left: 0px;
width: 250px;
height: 300px;
display: none;
}
#hover1 {
position: absolute;
float: left;
margin-top: 40px;
margin-left: 230px;
width: 50px;
height: 50px;
background: aqua;
}
#hover1:hover + .contact-box > #contact1 {
display: block;
}
#contact2 {
position: absolute;
float: left;
top: 0px;
left: 0px;
width: 250px;
height: 300px;
display: none;
}
#hover2 {
position: absolute;
float: left;
margin-top: 130px;
margin-left: 345px;
width: 30px;
height: 30px;
background: red;
}
#hover2:hover + .contact-box > #contact2 {
display: block;
}
#contact3 {
position: absolute;
float: left;
top: 0px;
left: 0px;
width: 250px;
height: 300px;
display: none;
}
#hover3 {
position: absolute;
float: left;
margin-top: 190px;
margin-left: 345px;
width: 30px;
height: 30px;
background: blue;
}
#hover3:hover + .contact-box > #contact3 {
display: block;
}
和HTML
<div class="main-map">
<div id="hover1"></div>
<div id="hover2"></div>
<div id="hover3"></div>
<div class="contact-box">
<div id="contact1">
This is a test.
</div>
<div id="contact2">
This is a test 2
</div>
<div id="contact3">
This is a test 3
</div>
</div>
</div>
答案 0 :(得分:2)
尝试将adjacent sibling selector +
替换为general sibling selector ~
。添加多个元素时它不起作用的原因是因为相邻的兄弟选择器使其仅适用于您的第三个项目,即hover3
,因为.contact-box
紧随其后。
即
#hover1:hover ~ .contact-box > #contact1 {
display: block;
}
<强> Demo 强>
另外,您实际上可以将其中一些规则概括并合并到:
HTML:
<div class="main-map">
<div id="hover1" class="hover"></div>
<div id="hover2" class="hover"></div>
<div id="hover3" class="hover"></div>
<div class="contact-box">
<div class="contact">This is a test.</div>
<div class="contact">This is a test 2</div>
<div class="contact">This is a test 3</div>
</div>
</div>
CSS:
.contact-box > .contact {
position: absolute;
float: left;
top: 0px;
left: 0px;
width: 250px;
height: 300px;
display: none;
}
#hover1 {
margin-top: 40px;
margin-left: 230px;
background: aqua;
}
#hover3 {
margin-top: 190px;
margin-left: 345px;
background: blue;
}
#hover2 {
margin-top: 130px;
margin-left: 345px;
background: red;
}
.hover {
position: absolute;
float: left;
width: 30px;
height: 30px;
}
.hover:nth-child(1):hover ~ .contact-box :nth-child(1),
.hover:nth-child(2):hover ~ .contact-box :nth-child(2),
.hover:nth-child(3):hover ~ .contact-box :nth-child(3) {
display: block;
}
<强> Demo 强>
答案 1 :(得分:0)
“+”是“相邻”兄弟选择器。相邻意味着直接相邻。
http://reference.sitepoint.com/css/adjacentsiblingselector
<h2>Heading</h2>
<p>The selector for this sibling is h2+p</p>
<p>The selector for this sibling is h2+p+p</p>