首页 > 解决方案 > div rollover 让子 div 改变颜色

问题描述

我在父 div 中有 3 个子 div,目前只有部分子 div 在鼠标悬停时改变颜色,我希望所有子 div 在部分鼠标悬停时改变颜色。谢谢

我试过下面的代码

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Untitled Document</title> 
        <style>
        .container {
            display: inline-block;
            cursor: pointer;
            width: 35px;
        }
        .bar1, .bar2, .bar3 {
            width: 35px;
            height: 5px;
            background-color: #333;
            margin: 6px 0;
            transition: 0.4s;
        }
        .bar1:hover, .bar2:hover, .bar3:hover {
            width: 35px;
            height: 5px;
            background-color: #e5e5e5;
            margin: 6px 0;
            transition: 0.4s;
        }
        </style>
    </head>
    <body>
        <div style=" text-align: right; padding-right: 30px;">
        <div class="container">
            <div class="bar1"></div>
            <div class="bar2"></div>
            <div class="bar3"></div>
        </div>
    </body>
</html>

标签: css

解决方案


您可以通过在悬停时选择父节点的子节点来完成此操作。

您当前的代码:

.bar1:hover, .bar2:hover, .bar3:hover {
    width: 35px;
    height: 5px;
    background-color: #e5e5e5;
    margin: 6px 0;
    transition: 0.4s;
}

... 将单独应用于每个元素(即,.bar3需要将其自身悬停以触发该状态)。

相反,您要选择的子元素.container:hover

.container:hover .bar1, .container:hover .bar2, .container:hover .bar3 {
    width: 35px;
    height: 5px;
    background-color: #e5e5e5;
    margin: 6px 0;
    transition: 0.4s;
}

这会将样式应用于:

  1. .bar1,container悬停时
  2. .bar2,container悬停时
  3. .bar3,container悬停时

编辑:起初我没有意识到这bar1是另外两个的兄弟姐妹。更新了我的答案以应用基于container:hover.


推荐阅读