如何在鼠标悬停父元素时触发子元素的CSS效果?
嘿,我明白你想要的效果了——当鼠标悬停在图片容器(父div#buttonStart)上时,让子div显示白色圆圈对吧?你找到的.parent:hover .child思路完全正确,只需要调整CSS选择器的关联逻辑就能实现,下面是具体的解决方案:
解决方案:父容器悬停触发子元素样式
核心思路就是把原来绑定在子元素自身hover上的样式,转移到父容器hover时的子元素上,这样只要鼠标碰到父容器(图片区域),子元素的白色圆圈效果就会触发。
步骤1:修改关键CSS选择器
找到原来针对子元素hover的规则,把它们的选择器替换为父容器hover时的子元素:
/* 移除或注释原来的子元素hover规则 */ /* .hovicon.effect-3.sub-b:hover, .hovicon.effect-3.sub-b:hover i { color: #696969; } */ /* .hovicon.effect-3.sub-b:hover:after { -webkit-transform: scale(1); -moz-transform: scale(1); -ms-transform: scale(1); transform: scale(1); opacity: 1; } */ /* 添加父容器hover触发子元素的规则 */ #buttonStart:hover .hovicon.effect-3.sub-b { cursor: pointer; color: #696969; } #buttonStart:hover .hovicon.effect-3.sub-b i { color: #696969; } #buttonStart:hover .hovicon.effect-3.sub-b:after { -webkit-transform: scale(1); -moz-transform: scale(1); -ms-transform: scale(1); transform: scale(1); opacity: 1; }
完整修改后的CSS代码
html { background: black; } #buttonStart { position: absolute; width: 15%; height: 10%; bottom: 15%; left: 5%; } #imageStart { width: 100%; height: 100%; } /* 父容器hover触发子元素样式的核心规则 */ #buttonStart:hover .hovicon.effect-3.sub-b { cursor: pointer; color: #696969; } #buttonStart:hover .hovicon.effect-3.sub-b i { color: #696969; } #buttonStart:hover .hovicon.effect-3.sub-b:after { -webkit-transform: scale(1); -moz-transform: scale(1); -ms-transform: scale(1); transform: scale(1); opacity: 1; } .hovicon { display: inline-block; font-size: 45px; line-height: 90px; cursor: pointer; width: 90px; height: 90px; border-radius: 50%; text-align: center; position: relative; text-decoration: none; z-index: 1; color: #fff; } .hovicon.auto-width { width: auto; height: auto; } .hovicon:after { pointer-events: none; position: absolute; width: 100%; height: 100%; border-radius: 50%; content:''; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; } .hovicon:before { speak: none; font-size: 48px; line-height: 90px; font-style: normal; font-weight: normal; font-variant: normal; text-transform: none; display: block; -webkit-font-smoothing: antialiased; } .hovicon.effect-3 { position: absolute; bottom:-13%; left: 62%; font-size: 3.8em; -webkit-transition: color 0.3s; -moz-transition: color 0.3s; transition: color 0.3s; } .hovicon.effect-3:after { top: -2px; left: -2px; padding: 2px; z-index: -1; background: #fff; -webkit-transition: -webkit-transform 0.2s, opacity 0.3s; -moz-transition: -moz-transform 0.2s, opacity 0.3s; transition: transform 0.2s, opacity 0.3s; } .hovicon.effect-3.sub-b, .hovicon.effect-3.sub-b i { color: #fff; }
HTML代码无需修改
<div id="buttonStart"> <div><input type="image" id="imageStart" src="https://cdn.pixabay.com/photo/2017/10/10/07/48/beach-2836300_960_720.jpg"> <div class="hovicon effect-3 sub-b" id="buttonStartEffect">   </div> </div> </div>
这样调整后,只要鼠标悬停在图片容器(父div)的任何区域,子元素的白色圆圈就会正常显示啦~
内容的提问来源于stack exchange,提问作者Arty_Prof
相关产品推荐
相关产品推荐

