鼠标悬浮image1时下移image2 5px 代码无效果原因咨询

代码问题点
- 事件绑定位置错误:
mouseleave事件绑定写在了jQuery(document).ready作用域外部,页面加载时DOM未渲染完成,找不到.image1元素导致绑定失效。 - CSS属性不生效:
top属性仅对非static默认定位的元素生效,未给.image2设置定位属性,添加类后也不会产生位移。 - 位移方向错误:需求为向下移动5px,
top: -5px是向上偏移,正确值应为top: 5px。 - 额外校验:确认两张图片分别添加了
image1、image2的类名,否则jQuery选择器无法匹配到对应元素。
修正后的jQuery代码
jQuery(document).ready(function($){ $('.image1').on('mouseenter', function() { $(".image2").addClass("move5px"); }); // 将mouseleave事件移入ready作用域内 $('.image1').on('mouseleave', function() { $(".image2").removeClass("move5px"); }); });
修正后的CSS代码
/* 给image2设置相对定位,top属性才会生效 */ .image2 { position: relative; /* 可选:添加过渡动画让位移更顺滑,不需要可删除 */ transition: all 0.2s ease; } .move5px { top: 5px; }
可选纯CSS实现方案(无需写JS)
如果image1和image2是同级相邻元素,直接用CSS hover选择器即可实现,更简单:
.image2 { position: relative; transition: all 0.2s ease; } /* 鼠标悬浮在image1上时,触发相邻image2的位移 */ .image1:hover + .image2 { top: 5px; }
内容的提问来源于stack exchange,提问作者Lyser
相关产品推荐
相关产品推荐

