鼠标悬停时更换图片图标显示但随鼠标移动消失问题求助
解决头像悬停时编辑按钮消失的问题
问题原因
当前代码通过相邻兄弟选择器 .profile__image:hover + .profile__change-image-button-hide 控制按钮显示,但编辑按钮是头像的相邻元素而非子元素。当鼠标从头像移到按钮上时,头像的:hover状态会消失,导致按钮随之隐藏,无法正常点击。
解决方案(两种任选其一)
方案一:将按钮嵌套到头像容器内
把编辑按钮放到.profile__image容器中,这样鼠标在按钮上时,依然处于头像容器的:hover状态,按钮不会消失。
修改后的HTML:
<div class="profile__user"> <div class="profile__image" title="An image of the French oceanographer- Jacques Cousteau"> <!-- 将按钮容器移入头像内部 --> <div class="profile__change-image-button-hide"> <button type="button" class="profile__change-image-button"> <img src="<%=require('./images/edit-profile-icon.svg')%>" alt="A vector image of a pen inside the profile image" class="profile__change-image-icon" /> </button> </div> </div> <div class="profile__info"> <h1 class="profile__title"></h1> <button type="button" class="profile__edit-button"> <img src="<%=require('./images/button-edit.svg')%>" alt="A vector image of a pen inside the edit button" class="profile__edit-icon" /> </button> <p class="profile__subtitle"></p> </div> </div>
修改后的CSS:
.profile__user { max-width: 583px; display: flex; position: relative; } .profile__image { background-size: cover; background-position: center; width: 120px; height: 120px; border-radius: 50%; display: flex; align-items: center; justify-content: center; /* 给头像容器添加相对定位,让内部按钮以此为基准定位 */ position: relative; } .profile__change-image-button { width: 26px; height: 26px; background: transparent; border: none; /* 相对于头像容器居中定位 */ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .profile__change-image-button-hide { display: none; } .profile__image:hover { opacity: 0.8; } /* 头像hover时显示内部的按钮容器 */ .profile__image:hover .profile__change-image-button-hide { display: block; }
方案二:利用父元素的hover状态(无需修改HTML)
通过父容器.profile__user的:hover状态控制头像透明度和按钮显示,只要鼠标在父容器范围内(包含头像和按钮),就保持效果。
修改后的CSS:
.profile__user { max-width: 583px; display: flex; position: relative; } .profile__image { background-size: cover; background-position: center; width: 120px; height: 120px; border-radius: 50%; display: flex; align-items: center; justify-content: center; } .profile__change-image-button { width: 26px; height: 26px; background: transparent; border: none; position: absolute; left: 47px; bottom: 56px; } .profile__change-image-button-hide { display: none; } /* 父容器hover时,修改头像透明度 */ .profile__user:hover .profile__image { opacity: 0.8; } /* 父容器hover时,显示按钮 */ .profile__user:hover .profile__change-image-button-hide { display: block; }
内容的提问来源于stack exchange,提问作者Natalie Shamir
相关产品推荐
相关产品推荐

