【问题标题】:hover affects all elements in class, how to make it only affect the one I'm hovering over?悬停影响类中的所有元素,如何使它只影响我悬停的元素?
【发布时间】:2023-03-14 11:25:01
【问题描述】:

我有一个带有各种按钮的菜单栏,当我将鼠标悬停在它们上方时,这些按钮会略微下拉并改变颜色。

更改颜色效果很好,但是当我将鼠标悬停在一个按钮上时,所有按钮都会下拉(而不仅仅是我悬停的那个)。

HTML:

<div id="menu">
    <div id="Button1" class="menuButton"></div>
    <div id="Button2" class="menuButton"></div>
    <div id="Button3" class="menuButton"></div>
</div>

CSS:

#menu {
    display: block;
    float: right;
    position: absolute;
    top:0;
    left:0;
    height: 30px;
}
.menuButton {
    width: 36px;
    height :40px;
    position: relative;
    display: inline-block;
    margin-top: -10px;
    background-color: rgba(200,50,50,0.25);
    transition: margin-top .3s, background-color .3s;
}
.menuButton:hover {
    margin-top: 0;
    background-color: rgba(100,100,255,0.6);
}

谁能弄清楚为什么会发生这种情况(以及我能做些什么来让它只有我悬停的元素才会出现)?

JSFiddle:http://jsfiddle.net/howkx1nv/

【问题讨论】:

    标签: html css hover css-transitions


    【解决方案1】:

    您的外部容器高度为 30 像素,而您的按钮为 40 像素,但底部边距为负数。

    当悬停在其中一个按钮上时,它会失去其上边距,从而将外部容器高度拉伸到 +10px,这会导致所有其他按钮填满整个 40px。

    话虽如此,代码中的罪魁祸首似乎是使用了内联块,因为块之间的行为会相互关联。如果您只是在原始小提琴中将display: inline-block 更改为float: left,您将看到正确的行为。

    【讨论】:

    • 这绝对有帮助。 jkris 给出了代码解决方案,但是你的评论应该可以帮助我理解这个问题,这样我以后就不会遇到类似的问题了。
    【解决方案2】:

    我已经更新了你的 jsFiddle 来完成你想要的:http://jsfiddle.net/howkx1nv/1/

    .menuButton {
        width: 36px;
        height :40px;
        position: relative;
        display: inline-block;
        margin-top: -10px;
        background-color: rgba(200,50,50,0.25);
        transition: top .3s, background-color .3s;
    }
    
    .menuButton:hover {
        position:relative;
        top:10px;
        background-color: rgba(100,100,255,0.6);
    }
    

    SquareCat 解释了为什么所有 div 都在向外窥视的现象。

    【讨论】:

    • 谢谢!另一个问题,为什么过渡不再在那个小提琴上起作用?该按钮似乎是向下滑动而不是平滑地向下滑动。
    • 检查.menuButton 上的transition 属性,看看它是否仍在使用margin-top 而不是top
    • 其实只是在.menuButton中没有定义top而已。添加顶部:0;到 menuButton 似乎可以做到这一点。不过感谢您的帮助。
    • 哦.. 我在 safari 上查看此内容,因此在没有 top:0 到 menuButton 的情况下它可以正常工作。未来需要注意的事项。
    猜你喜欢
    • 2013-08-01
    • 2021-06-19
    • 1970-01-01
    • 2021-01-15
    • 2011-05-29
    • 2019-01-27
    相关资源
    最近更新 更多