如果我的mouseenter函数已经执行,我怎么能不执行它?

时间:2016-04-01 18:22:28

标签: javascript jquery events dom javascript-events

简单问题:所以我有一个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');
        });

    });

我希望它只在尚未执行的过程中执行。原因是因为我不想让某人重新盘旋在这件事上,并在它仍在制作动画时开始播放。

1 个答案:

答案 0 :(得分: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;
        }
});