要在悬停子元素时更改父元素的颜色,您需要使用JavaScript,因为CSS本身不支持选择父元素
<!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
元素添加了mouseover
和mouseout
事件监听器,这些监听器会分别在鼠标指针悬停在子元素上时和离开时触发。当这些事件触发时,我们分别将父元素的背景颜色设置为红色和浅绿色。这样,您就可以实现在悬停子元素时更改父元素颜色的效果了。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云