【问题标题】:jQuery assign event handler with timeouts per elementjQuery为每个元素分配超时事件处理程序
【发布时间】:2013-06-02 20:50:48
【问题描述】:

对我来说很有趣。我有一个视频播放器,其控件在悬停时显示。最初,我使用 CSS 执行此操作,但必须将策略更改为 javascript 才能与浏览器全屏 api 配合使用(顺便说一句,这意味着您总是将鼠标悬停在视频上)。

我的新方法是为视频容器设置mousemove 的事件处理程序,该容器添加一个类并设置一个超时来删除它,如果已经设置了超时,则将其清除。这很有效,但逻辑并不能扩展到一个以上的玩家。

TLDR:如何扩展我的逻辑以扩展到多个视频容器? time 变量的范围需要包含在每个元素事件中,但也需要在处理程序之外,以便可以从一个事件到下一个事件(在同一个元素上)清除它。

感谢您的帮助 - 这些逻辑问题对我来说总是很困难。

这是jsFiddle example。您会注意到,当您将悬停限制在一个元素时效果很好,但是当您扩展到页面上的其余元素时,就会出现问题。

HTML:

<div class="cont">

    <div class="controls">controls</div>
</div>

JavaScript:

var time;

$('body').on('mousemove', '.cont', function(){

    var thiis = $(this);

    if (time){

        clearTimeout(time);
    }

    thiis.addClass('showControls');

    time = setTimeout(function(){

        thiis.removeClass('showControls');
    }, 2000);
});

【问题讨论】:

    标签: javascript variables event-handling scope timeout


    【解决方案1】:

    您可以使用 jQuery 的 data 方法存储时间变量,该方法可以存储每个元素的数据。

    $('body').on('mousemove', '.cont', function(){
    
      var thiis = $(this),
          // get the time from the data method
          time = thiis.data("timer-id");
    
       if (time){
         clearTimeout(time);
       }
    
      thiis.addClass('showControls');
    
       var new_time = setTimeout(function(){
        thiis.removeClass('showControls');
       }, 2000);
    
       // save the new time
      thiis.data("timer-id", new_time);
    });
    

    【讨论】:

    • thiis 看起来像是一个错字。例如,如果您使用_this,可能会更清楚一些......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    • 2017-12-02
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多