jQuery为每个元素分配事件处理程序超时

tec*_*ant 3 javascript variables scope timeout event-handling

有趣的一个对我来说.我有一个视频播放器,当悬停时显示控件.最初,我用CSS做了这个,但不得不将策略改为javascript,以便与浏览器全屏api一起玩(顺便说一句,这意味着你总是徘徊在视频上).

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

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

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

这是一个jsFiddle示例.当您将鼠标悬停限制为一个元素时,您会注意到它很有效,但是当您扩展到页面上的其余元素时会出现问题.

HTML:

<div class="cont">

    <div class="controls">controls</div>
</div>
Run Code Online (Sandbox Code Playgroud)

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);
});
Run Code Online (Sandbox Code Playgroud)

ibl*_*ish 5

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

$('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);
});
Run Code Online (Sandbox Code Playgroud)