You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

image1 with its reflection (image2)

代码问题点

  • 事件绑定位置错误: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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 09:39:04