【问题标题】:Prevent subsequent firings after initial .mousedown() event with jQuery使用 jQuery 在初始 .mousedown() 事件后防止后续触发
【发布时间】:2014-03-02 02:28:29
【问题描述】:

问题描述 (Fiddle):

多次单击 #test 框会创建同时播放的音频层,并在每次按下时短暂暂停或错开.fadeOut() 效果。我想防止触发后续的 mousedown 事件,以便 .fadeOut() 效果无缝完成并且不会触发额外的音频播放。

代码:

$('#test').mousedown(function() {
  var sound = new Audio("http://sounddogs.com/previews/3668/mp3/824357_SOUNDDOGS__ri.mp3");
  sound.play();
  $('#test').stop(true).fadeOut(2000);
});

【问题讨论】:

  • 喜欢这个? api.jquery.com/one
  • 这很酷,我从来不知道它存在。谢谢你教育我!
  • 很高兴它有帮助...我不确定这是否是您的意思,所以我会回答一下

标签: javascript jquery html audio


【解决方案1】:

这将触发一次事件:http://api.jquery.com/one/

【讨论】:

    【解决方案2】:

    简单的方法:

    var clicked = 0;
    $('#test').mousedown(function () {
        if (clicked == 0) {
            clicked = 1;
            var sound = new Audio("http://sounddogs.com/previews/3668/mp3/824357_SOUNDDOGS__ri.mp3");
            sound.play();
            $('#test').stop(true).fadeOut(2000);
            setTimeout(function(){clicked = 0;}, 2000);
        }
    });
    

    http://jsfiddle.net/yxDSL/1/

    【讨论】:

    • 我一直在我的代码的其他区域实施此解决方案,但它在这里不起作用;原来问题是我通过调用另一个函数来重置我的clicked 变量。只需要将其移出范围,问题就解决了。这是迄今为止最好的解决方案,我从来没有想过使用 setTimeout 进行重置。如此简单,却又如此精彩。谢谢。
    【解决方案3】:
     $('#test').one('click',function() { //would only trigger on first click
      var sound = new Audio("http://sounddogs.com/previews/3668/mp3/824357_SOUNDDOGS__ri.mp3");
      sound.play();
     $('#test').stop(true).fadeOut(2000);
    
     $('#test').click(function(){ // for subsequent click write the function inside this
    
     });
    });
    

    【讨论】:

    • 我不知道 .one() 函数甚至存在。这在未来将非常有帮助,但不太适合我的需求。非常感谢。
    【解决方案4】:

    这样就可以了……

    $('#test').mousedown(function() {
      var sound = new Audio("http://sounddogs.com/previews/3668/mp3/824357_SOUNDDOGS__ri.mp3");
      sound.play();
      $('#test').unbind("mousedown").stop(true).fadeOut(2000);`
    }); 
    

    【讨论】:

    • 谢谢您,先生。我什至从未想过将 .unbind() 函数用于这样的事情。你知道的越多……
    • 没问题,简短而简单:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 1970-01-01
    • 2013-09-07
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多