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

如何在窗口宽度小于300px时关闭jQuery的.hover()事件

问题原因

jQuery 的 .hover() 方法并非绑定了一个名为 hover 的事件,而是同时绑定了 mouseenter 和 mouseleave 两个原生事件。所以你用 .off("hover") 无法找到对应的事件处理函数,自然无法移除 hover 效果。

解决方案

方案1:直接移除对应原生事件

把 else 分支里的代码改成移除 mouseenter 和 mouseleave 事件即可,同时注意在绑定前先移除旧事件,避免重复绑定导致多次触发:

$(window).on("resize", function() {
  if ($(window).width() > 300) {
    // 绑定前先移除,防止多次resize重复绑定
    $(".link").off("mouseenter mouseleave")
              .hover(function() {
                $(this).text("Alternative Text");
              }, function() {
                $(this).text("Hover me");
              });
  } else {
    $('.link').off("mouseenter mouseleave");
  }
}).resize();

方案2:使用事件命名空间(更严谨)

如果页面中其他地方也给 .link 绑定了 mouseenter/mouseleave 事件,直接移除会影响其他逻辑。这时可以给 hover 事件加上命名空间,精准控制:

$(window).on("resize", function() {
  const $link = $(".link");
  if ($(window).width() > 300) {
    // 移除同命名空间的事件,再重新绑定
    $link.off("mouseenter.hoverToggle mouseleave.hoverToggle")
         .on("mouseenter.hoverToggle", function() {
           $(this).text("Alternative Text");
         })
         .on("mouseleave.hoverToggle", function() {
           $(this).text("Hover me");
         });
  } else {
    // 只移除我们自己加的hover相关事件
    $link.off("mouseenter.hoverToggle mouseleave.hoverToggle");
  }
}).resize();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 15:30:41