我有一堆div在彼此之上,设置为position:absolute,全部包含在容器div中。我想要做的是当用户将鼠标悬停在#feature_1_hitbox上时更改#feature_1_shade的背景位置。我试图通过使用 -
来实现这一目标#feature_1_hitbox:hover #feature_1_shade {
background-position: 0 0;
}
这不起作用。但是,如果我将它应用于容器div,它会起作用:
#feature_1_container:hover #feature_1_shade {
background-position: 0 0;
}
我几乎满足于此,但我需要将hitbox设置为特定大小,因此:hover必须应用于我的hitbox div。有没有理由为什么这适用于一个div而不是另一个?
这是标记代码:
<!-- container --> <div id="feature_1_container">
<!-- shade --> <div id="feature_1_shade"></div>
<!-- text and arrow --> <div id="feature_1_text_container"><h3 id="feature_1_arrow">Memberships</h3><p id="feature_1_text">Text here text here</p></div>
<!-- image --> <div id="feature_1_graphic"></div>
<!-- hitbox --> <a href="#"><div id="feature_1_hitbox"></div></a>
</div> <!-- #feature_1_container -->
这是CSS:
#feature_1_container {
width: 289px;
height: 255px;
float: left;
}
#feature_1_hitbox {
width: 289px;
height: 166px;
margin: 89px 0 0 0;
position: absolute;
/* background-color: #F99; */
}
#feature_1_graphic {
width: 289px;
height: 255px;
position: absolute;
background-image: url(site_style_images/feature_1_memberships_bag.png);
}
#feature_1_text_container {
width: 289px;
margin: 100px 0 0 0;
position: absolute;
}
#feature_1_text {
margin: 0 0 0 100px;
}
#feature_1_arrow {
background-image: url(site_style_images/feature_arrows.png);
background-position: center right;
background-repeat: no-repeat;
height: 49px;
padding: 0 30px 0 100px;
margin: 0 22px 0 0;
color: #8d895c;
font-size: 22px;
line-height: 44px;
font-family: 'Quicksand', sans-serif;
font-weight: normal;
letter-spacing: -2px;
font-style: normal;
}
#feature_1_shade {
width: 289px;
height: 166px;
margin: 89px 0 0 0;
background-image: url(site_style_images/feature_1_shade.png);
background-position: 0 -166px;
position: absolute;
background-color: #CCC;
}
#feature_1_hitbox:hover #feature_1_shade {
background-position: 0 0;
}
答案 0 :(得分:1)
按照该顺序使用HTML源代码,您将不得不使用JavaScript或jQuery。 CSS选择器不能向后引用先前的元素。
如果源订单被撤消,您可以执行以下操作:
#feature_1_hitbox:hover ~ a #feature_1_shade
如果jQuery是一个选项,您可以根据#feature_1_shade
的hove状态添加和删除一个类#feature_1_hitbox
:
CSS
#feature_1_shade.on {...}
的jQuery
$("#feature_1_hitbox").hover(
function(){ $('#feature_1_shade').addClass('on'); },
function(){ $('#feature_1_shade').removeClass('on'); }
);
JavaScript等价物是:
var obj = document.getElementById("feature_1_hitbox");
obj.onmouseover = function(){
document.getElementById("feature_1_shade").className = "on";
}
obj.onmouseout = function(){
document.getElementById("feature_1_shade").className = "";
}
注意:如果#feature_1_shade
使用任何其他类,则在使用纯JavaScript添加或删除类时必须小心。
答案 1 :(得分:0)
它不起作用的原因是因为对于CSS选择器,#container:hover #shade {}实际上在ID #container中为ID #shade INSIDE设置了样式。在您的标记代码中,#shade嵌套在#container中,但不在#hitbox中。也许添加另一个“隐形div”(不透明度:0),其大小和位置与hitbox完全相同,并且包括隐形div内的阴影,然后使用其悬停选择器设置隐形div可能会起作用。示例:#invisible_hitbox_hover:hover #shade {}