【问题标题】:How can I make my mouseenter function not execute if it's already executing?如果我的 mouseenter 函数已经在执行,如何让它不执行?
【发布时间】:2016-07-21 16:07:13
【问题描述】:

简单的问题:所以我有一个mouseenter 函数

    $('.filmstrip').bind('mouseenter',function(){
        var isStopped = false;
        var $that = $(this),
               w = $that.width(),
              fr = $that.attr('data-framerate');
        $that.css('background-position',$that.attr('data-placeholderXStart') + ' center');
        $that.css('background-image','url('+$that.attr('data-gifurl')+')');
        for ( var i = 1, n = $that.attr('data-ticks'); i <= n && !isStopped; ++i )
        {
            (function(j){
               setTimeout(function(){
                  if (!isStopped) {
                      $that.css('background-position','-'+(w*j)+'px center');
                  }
               }, j*fr);
            })(i);
        }
        $that.bind('mouseleave',function(){
            isStopped = true;
            $that.css('background-image','url('+$that.attr('data-placeholder')+')').css('background-position',$that.attr('data-placeholderXStart') + ' center');
        });
        
    });

并且我希望它仅在它尚未处于执行过程中时才执行。原因是因为我不希望有人将鼠标重新悬停在该事物上并使其在其仍处于动画状态时启动。

【问题讨论】:

  • isStopped 放在事件处理程序之外。
  • @adeneo 所以让它成为一个全局变量?
  • 这取决于事件处理程序之外的范围。我个人会使用 jQuery 的data()。然而,该变量确实需要在事件处理程序之外持续存在,因此如果再次触发处理程序,它就知道动画正在进行中

标签: javascript jquery dom events jquery-events


【解决方案1】:

创建一个全局变量,指示与鼠标输入事件相关的函数状态

    var isMouseEnterRunning = false;
    $('.filmstrip').bind('mouseenter',function(){

        if(!isMouseEnterRunning){ 
            isMouseEnterRunning = true;   
            var isStopped = false;
            var $that = $(this),
                   w = $that.width(),
                  fr = $that.attr('data-framerate');
            $that.css('background-position',$that.attr('data-placeholderXStart') + ' center');
            $that.css('background-image','url('+$that.attr('data-gifurl')+')');
            for ( var i = 1, n = $that.attr('data-ticks'); i <= n && !isStopped; ++i )
            {
                (function(j){
                   setTimeout(function(){
                      if (!isStopped) {
                          $that.css('background-position','-'+(w*j)+'px center');
                      }
                   }, j*fr);
                })(i);
            }
            $that.bind('mouseleave',function(){
                isStopped = true;
                $that.css('background-image','url('+$that.attr('data-placeholder')+')').css('background-position',$that.attr('data-placeholderXStart') + ' center');
            });
            isMouseEnterRunning = false;
        }
});

【讨论】:

    猜你喜欢
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 2012-05-20
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多