使用jQuery初始化.mousedown()事件后防止后续触发

时间:2014-03-02 02:28:30

标签: javascript jquery html audio

问题描述(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);
});

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

 $('#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

 });
});

答案 2 :(得分:1)

简单方法:

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/

答案 3 :(得分:1)

这就是诀窍......

$('#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);`
});