
本文旨在解决SVG hover效果在独立环境中工作正常,但集成到card组件后失效的问题。通过分析CSS样式和HTML结构,我们将定位问题根源,并提供清晰的解决方案,确保hover效果在card组件中也能正确呈现。重点在于理解`z-index`属性对hover事件的影响,以及如何调整CSS选择器以确保样式正确应用。
当SVG元素单独存在时,其hover效果可能正常工作。然而,当将其嵌入到更复杂的HTML结构中,如card组件时,hover效果可能会失效。这通常是由于以下原因:
针对上述问题,可以采取以下步骤解决:
移除 z-index: -1
立即学习“前端免费学习笔记(深入)”;
这是最直接有效的解决方案。从.center__div--heartFilled类中移除z-index: -1。这个属性导致填充的心形位于轮廓心形的下方,从而阻止了hover事件的触发。
.center__div--heartFilled {
/* z-index: -1; 移除此行 */
}检查CSS选择器优先级
确保.card__heart:hover .svg__heart--filled选择器的优先级高于其他可能影响SVG样式的选择器。可以使用浏览器的开发者工具检查哪些样式正在应用到SVG元素,以及它们的来源。如果发现有其他选择器覆盖了hover样式,可以尝试增加.card__heart:hover .svg__heart--filled选择器的特异性(例如,通过添加更多的类名或使用!important声明,但通常不推荐过度使用!important)。
确认HTML结构
确保SVG元素在HTML结构中正确嵌套。在提供的代码中,SVG元素嵌套在.center__div和.card__heart等元素中。确保这些元素的结构没有问题,并且没有其他元素遮挡SVG元素。
以下是修改后的CSS代码:
body {
background: black;
}
body a {
text-decoration: none;
color: black;
}
.card {
width: 90%;
height: 225px;
margin-bottom: 25px;
border-radius: 15px;
overflow: hidden;
}
.card__image {
height: 160px;
}
.card__image img {
width: 100%;
height: 100%;
object-fit: cover;
}
.card__body {
height: 65px;
width: 100%;
display: flex;
align-items: center;
flex-flow: row wrap;
justify-content: space-between;
background: white;
}
.card__title {
padding-left: 15px;
display: flex;
flex-flow: column wrap;
gap: 3px;
}
.card__title h3 {
margin-top: 0px;
margin-bottom: 0px;
}
.card__title p {
margin-top: 0px;
margin-bottom: 0px;
}
.card__heart {
margin-right: 40px;
border: solid black 1px;
position: relative;
display: flex;
justify-content: center;
align-items: center;
width: 32px;
height: 32px;
}
/* styliser les svg heart */
.center__div {
width: 32px;
height: 32px;
position: absolute;
cursor: pointer;
}
.center__div--heartFilled {
/* z-index: -1; 移除此行 */
}
.svg__heart--filled {
opacity: 0;
transition: all 500ms ease-in-out;
}
.card__heart:hover .svg__heart--filled {
opacity: 1;
}
/*.
.svg__heart--filled {
opacity: 1;
}
*/
.svg__heart--outline {
background: rgba(0, 0, 0, 0);
}
.color-primary {
stop-color: yellow;
stop-opacity: 1;
}
.color-secondary {
stop-color: red;
stop-opacity: 1;
}当SVG hover效果在独立环境中工作正常,但在card组件中失效时,通常是由于层叠上下文、CSS选择器优先级或事件冒泡等问题引起的。通过移除不必要的z-index属性,检查CSS选择器优先级,并确保HTML结构正确,可以解决这些问题,使hover效果在card组件中也能正常工作。理解CSS的层叠规则和选择器优先级是解决此类问题的关键。
以上就是解决CSS Hover效果在独立SVG元素中有效,但在Card集成中失效的问题的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号