css - Div 未正确显示悬停功能

标签 css html

我在一个包含的 div 中有两个 div。

两者中的第一个将有一个用作菜单项的词,第二个将包含背景颜色。

我为背景创建了一个悬停样式,当鼠标悬停在菜单项上时,该样式将更改该 div 的不透明度。

我的问题是只有当鼠标正好位于 div 的边缘时才会启用悬停。只要我的鼠标稍微移入 div 的内部,它就会恢复到原来的不透明度。

我的风格:

.menuItemBG {
    width:100%;
    text-align: center;
    background-color:#4281b6;
    height:100%;

    /* These three lines are for transparency in all browsers. */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=10)";
    filter: alpha(opacity=10);
    opacity:.1;
    position: absolute;
}
.menuItemBG:hover {
    width:100%;
    text-align: center;
    background-color:#4281b6;
    height:100%;

    /* These three lines are for transparency in all browsers. */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=20)";
    filter: alpha(opacity=20);
    opacity:.2;
    position: absolute;
}
.menuItemTitle{
    position:relative;
    color:#000;
    line-height: 27px;
    font-size: 14px;
    margin-left: 20px;
}

HTML:

<div style="position:relative; width:208px; height:30px;">
    <div class="menuItemBG"></div>
    <div class="menuItemTitle">Test Item</div>
 </div>

似乎无法查明我的错误。

最佳答案

当您将鼠标悬停在 menuItemTitle 上时,您不再将鼠标悬停在 menuItemBG 上,因为它们是 DOM 中的兄弟。您可以将 :hover 切换到包含它们的 div,并以这种方式将样式应用于 menuItemBG。如果你给包含的 div 类 menuItem,你可以这样做:

.menuItem:hover .menuItemBG {
    /* These three lines are for transparency in all browsers. */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=20)";
    filter: alpha(opacity=20);
    opacity:.2;
}

请注意,我没有重复经常应用于 .menuItemBG 的 CSS。不需要。然后将类 menuItem 添加到包含的 div 中:

<div class="menuItem">
    <div class="menuItemBG"></div>
    <div class="menuItemTitle">Test Item</div>
</div>

您现在可以很容易地将 .menuItem 的内联 CSS 移动到您的样式表中。它以任何一种方式工作,但将其移至样式表更清晰且更易于维护。

.menuItem {
    position: relative;
    width: 208px;
    height: 30px;
}

演示:http://jsfiddle.net/fYQfX/1

关于css - Div 未正确显示悬停功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18476656/

相关文章:

javascript - 获取表格单元格内容以在页面上向上移动

javascript - 调整窗口大小时刷新浏览器(仅在扩展或变大时)

html - Angular 5 下拉框中的下拉列表消失

jquery - 我如何滚动父 div,子 div 溢出的地方?

javascript - 当我将鼠标快速移出绘图时,jQuery flot 工具提示不会隐藏

html - CSS使表格自动从thead变成一列标签

css - RGBa 与不透明度(特别是 BBC slider )

php - HTML5 视频播放转换器

HTML/CSS Logo 放置问题

javascript - 当没有元素,只有文本时抓取innerHTML