【问题标题】:Disabling a jquery hover function with a click function使用单击功能禁用 jquery 悬停功能
【发布时间】:2012-11-13 09:26:44
【问题描述】:

我们有一个图库,当您将光标悬停在图像 div 上时,标题会淡出。我们的下一步是添加一个显示所有字幕的按钮,这样人们就可以滚动和阅读,而无需在屏幕上移动光标。

创建 showall 函数很容易,但是当光标经过任何照片时,悬停函数会触发并且该图像上的标题会消失。

有没有一种简单的方法可以让 showall 功能在 showall 处于活动状态时禁用悬停功能?

我们的基本 jquery 代码如下,.tease 是标题:

$('.tease').hide();
$('.img33, .img40, .img50, .img60').hover(
    function(){ $(this).children('.tease').fadeIn('900'); },
    function(){ $(this).children('.tease').fadeOut('2500'); }
);

每张图片的基本html:

<div class="img33">
<img src="../dir/someimage.jpg">
<div class="tease">Tease copy</div>
</div>

【问题讨论】:

  • 我可以看看你的showall方法的点击功能,以便我可以正确回答这个问题。

标签: jquery click hover


【解决方案1】:

您可以只定义一个在悬停函数中检查的全局变量。

例如

var hoverEnabled = true;

$('.tease').hide();
$('.img33, .img40, .img50, .img60').hover(
    function(){ if(hoverEnabled) $(this).children('.tease').fadeIn('900'); },
    function(){ if(hoverEnabled) $(this).children('.tease').fadeOut('2500'); }
);

$('#showAllButton').click(function() {
    $('.tease').show();
    hoverEnabled = false;
}

或者,您可以在 showall 函数中使用 .bind() 和事件名称(例如 hover.showTease)和 .unbind() 绑定悬停事件。

【讨论】:

    【解决方案2】:

    你可以这样解绑“悬停”:

    $(this).unbind('mouseenter mouseleave');
    

    只需在您想禁用悬停时执行此操作。或者,为了更好地控制而不是继续添加和删除事件,您可能希望引入一个添加和删除的类,并且仅在将某个类设置为元素时才执行悬停动作。像这样:

    $(this).hover(
        function() { 
            if ($(".yourElement").hasClass("allowHover")) { 
                ... 
            }  
        },
        function() { 
            if ($(".yourElement").hasClass("allowHover")) { 
                ... 
            }  
        }
     );
    

    然后只需添加或删除一个类,悬停就会启用或禁用。

    【讨论】:

      【解决方案3】:
      var allShown = false;
      
      function showAll(){
          //some imaginary code
      
          //we're showing all
          allShown = true;
      }
      

      这应该是 DOM 准备好的范围。

      $(function(){
         $('.img33, .img40, .img50, .img60').hover(function(){ 
              if(allShown === false){
                  $(this).children('.tease').fadeIn('900');
              }
          },function(){  
              if(allShown === false){
                  $(this).children('.tease').fadeOut('2500');
              }
          });
      
          $('ele').on('something', function(){
              //some code..
              allShown = false;
          });
      
          //some event to fire the showAll function
          $('ele').on('something', function(){
              showAll();
              allShown = true;
          });
      
      
      
      });
      

      【讨论】: