mouseenter事件触发区域不符合预期:hover父容器picture_batch_container时意外触发评论图标显示
嘿,我找到你问题的根源啦!
你的问题其实出在CSS Grid布局的默认行为上:你把.img_container_invis放在了.picture_batch_container这个Grid容器里,Grid布局默认会把所有子元素(也就是Grid Item)的尺寸拉伸到填满整个网格单元格。哪怕你给.img_container_invis加了display: inline-block也没用——Grid规范会直接忽略Grid Item的display属性,导致这个容器实际上占满了整个600x600的大容器区域。这就解释了为什么鼠标一碰到大容器,评论图标就弹出来了,因为整个大容器都是.img_container_invis的范围!
怎么解决?
很简单,我们只需要修改.img_container_invis的Grid对齐属性,让它只包裹内部的图片,别乱拉伸:
给.img_container_invis加上这两个CSS属性:
justify-self: start; align-self: start;
这会让它在Grid里靠左、靠上对齐,尺寸完全由内部的图片决定,不会再填满整个大容器了。
修改后的完整代码示例
CSS 部分
.picture_batch_container { display: grid; height: 600px; width: 600px; border: 5px solid red; background-color: grey; margin: auto; } .picture_batch_container_img { width: 200px; height: 200px; object-fit: contain; } .img_container_invis { position: relative; /* 关键修复:让容器只包裹内容,不拉伸 */ justify-self: start; align-self: start; } #img_comment_icon { width: 30px; height: 30px; font-size: 10px; font-family: consolas; position: absolute; display: none; text-shadow: 0px 0px 5px black; object-fit: contain; /* 额外优化:把图标定位到图片右上角 */ top: 10px; right: 10px; }
JavaScript 部分(你的逻辑是对的,不用改)
const imgCommentIcon = document.getElementById('img_comment_icon'); document.querySelectorAll('.picture_batch_container_img').forEach(function(img) { const container = img.parentElement; container.addEventListener('mouseenter', function() { imgCommentIcon.src = img.dataset.comment; imgCommentIcon.style.display = 'block'; }); container.addEventListener('mouseleave', function() { imgCommentIcon.style.display = 'none'; }); });
HTML 部分(也不用改)
<section> <div class="picture_batch_container"> <div class="img_container_invis"> <img src="300by300.webp" class="picture_batch_container_img" data-comment="comment.png"> <img id="img_comment_icon" src="comment.png"> </div> </div> </section>
额外小建议
- 如果你之后要在Grid里放多个图片容器,这个方案依然管用,每个容器都会老老实实包裹自己的图片;
- 调试的时候可以给
.img_container_invis临时加个border: 1px solid blue,就能直观看到它的范围是不是正常了; - 评论图标加个定位后,用户体验会更好,不会乱跑~
内容的提问来源于stack exchange,提问作者Best Programmer
相关产品推荐
相关产品推荐

