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

jQuery如何实现hover触发scrollTo滚动事件执行一次后自动解绑?

实现masthead hover滚动仅触发一次的方案

方案1:直接使用one()绑定单次执行事件

jQuery内置的one()方法本身支持绑定的事件处理函数仅执行一次,是最简单的实现方式。
注意你原代码使用的hover()是mouseenter+mouseleave的快捷方法,仅传一个回调时移入移出都会触发,建议明确绑定mouseenter事件仅在鼠标移入时触发:

$('.home #masthead').one('mouseenter', function(){
  $("body").scrollTo($(this), 1000);
});

方案2:执行后手动解绑事件

如果你需要保留更多控制逻辑,也可以在回调执行完成后调用off()方法解绑对应事件:

$('.home #masthead').on('mouseenter', function(){
  $("body").scrollTo($(this), 1000);
  // 执行完成后解绑当前元素的mouseenter事件
  $(this).off('mouseenter');
});

UX优化建议

你提到的设计确实存在小概率误触问题,可以加一个短延迟判定,只有鼠标在masthead上停留超过指定时长(比如200ms)才触发滚动,避免用户快速划过页面时误触发:

let hoverDelayTimer;
$('.home #masthead').one('mouseenter', function(){
  const $masthead = $(this);
  hoverDelayTimer = setTimeout(() => {
    $("body").scrollTo($masthead, 1000);
  }, 200);
}).one('mouseleave', function(){
  // 鼠标提前移出则取消待执行的滚动逻辑
  clearTimeout(hoverDelayTimer);
});

内容的提问来源于stack exchange,提问作者Chris Pink

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:48:03