【问题标题】:jQuery Toggle and Hover functionailityjQuery 切换和悬停功能
【发布时间】:2026-01-10 09:55:01
【问题描述】:

所以我有一个元素可以在单击时在两种背景颜色之间切换。但是当没有选择元素时,我希望背景颜色在悬停时改变(并恢复)。我尝试在切换中使用 .on('hover') 和 .off('hover') ,但似乎只有 .off() 有效。

$('.element').hover(
  function() {
    $(this).css('background', '#e7f1f5');
  },
  function() {
    $(this).css('background', '#fff');
  }
);

$('.element').toggle(
  function( select ) {
    select.preventDefault();
    $(this).off('hover');
    $(this).css('background', '#f6f6f6');
    other.code();
  },
  function( unselect ) {
    unselect.preventDefault();
    $(this).on('hover');
    $(this).css('background', '#fff');
    other.code();
  }
);

我切换“开”,“悬停”事件不再触发(根据需要)。 当我切换“关闭”时,“悬停”事件仍然不会触发。

我对 jQuery 和 * 还很陌生,所以如果这个问题是微不足道的,我很抱歉。

谢谢!

【问题讨论】:

    标签: jquery hover toggle bind


    【解决方案1】:

    使用css:

    .element{
       background-color:#FFF;
    }
    .element.hover{
       background-color:#e7f1f5;
    }
    

    代替$(this).off('hover'); 做:

    $(this).addClass('hover');
    

    代替$(this).on('hover'); 做:

    $(this).removeClass('hover');
    

    【讨论】:

    • 抱歉,这不起作用。将元素切换为“打开”后,悬停事件应该不起作用。这似乎没有解决这个问题。
    • @MichaelChoi 尝试使用$(this).hover(); 而不是on
    • 我什至没有想过改变css中的悬停。谢谢!