首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在悬停子元素时更改父元素的颜色

要在悬停子元素时更改父元素的颜色,您需要使用JavaScript,因为CSS本身不支持选择父元素

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Change Parent Color on Child Hover</title>
    <style>
        .parent {
            background-color: lightgreen;
            width: 200px;
            height: 200px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .child {
            background-color: orange;
            width: 100px;
            height: 100px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
    </style>
</head>
<body>
    <div class="parent">
        <div class="child">
            Hover me
        </div>
    </div>

    <script>
        const childElement = document.querySelector('.child');
        const parentElement = document.querySelector('.parent');

        childElement.addEventListener('mouseover', () => {
            parentElement.style.backgroundColor = 'red';
        });

        childElement.addEventListener('mouseout', () => {
            parentElement.style.backgroundColor = 'lightgreen';
        });
    </script>
</body>
</html>

在这个例子中,我们有一个名为.parent的外部div,其子DIV名为.child。我们为.child元素添加了mouseovermouseout事件监听器,这些监听器会分别在鼠标指针悬停在子元素上时和离开时触发。当这些事件触发时,我们分别将父元素的背景颜色设置为红色和浅绿色。这样,您就可以实现在悬停子元素时更改父元素颜色的效果了。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券