0

我有一堆 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;
}
4

2 回答 2

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 添加或删除类时必须小心。

于 2012-06-24T21:40:44.420 回答
0

它不起作用的原因是因为对于 CSS 选择器,#container:hover #shade{} 实际上将 ID #shade 设置在 ID #container 内。在您的标记代码中,#shade 嵌套在 #container 中,但不在 #hitbox 中。也许添加另一个“不可见 div”(不透明度:0),其大小和位置与 hitbox 完全相同,并在不可见 div 内包含阴影,然后使用悬停选择器设置不可见 div 的样式可能会起作用。示例:#invisible_hitbox_hover:hover #shade{}

于 2012-06-30T09:19:07.400 回答