在动画完成之前防止多次点击(jQuery)

时间:2013-04-23 09:14:29

标签: jquery

我有一个带缩略图的图库,当点击缩略图时,当前图像淡出,新图像淡入。

但是,我希望停止多次点击,因此在点击新缩略图之前,图片必须完全淡出。

如何使用以下代码执行此操作?

非常感谢,

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>TEST</title>
<script type='text/javascript' src='jquery-1.9.1.js'></script>

<style type='text/css'>
#imageWrap{
position:relative;
overflow:hidden;
height:534px;
width:800px;
}
.next{
display:none;
}
#imageWrap img{
width: 800px;
position: absolute;
top: 0;
left: 0;
background-color: #000;
}
</style>

<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
$('.thumbnail').on('click',function(){
$('#imageWrap').append('<img src="' + $(this).attr('src') + '" class="next" />');
$('#imageWrap .active').fadeOut(5500);
$('#imageWrap .next').fadeIn(4000, function(){
    $('#imageWrap .active').remove();
    $(this).addClass('active');
});

});
});//]]>  

</script>

</head>
<body>
<img src="dimming/1.jpg" class="thumbnail" alt="A" width="40" height="40"/>
<img src="dimming/2.jpg" class="thumbnail" alt="B" width="40" height="40"/>
<img src="dimming/C.jpg" class="thumbnail" alt="C" width="40" height="40"/>
<img src="dimming/D.jpg" class="thumbnail"alt="D" width="40" height="40"/>
<img src="dimming/E.jpg" class="thumbnail" alt="E" width="40" height="40"/>

<div id="imageWrap">
    <img src="dimming/C.jpg" alt="Main Image" width="800" height="534" class="active" />
</div>
</body>
</html>

2 个答案:

答案 0 :(得分:5)

通过添加一个布尔标志,您可以在决定做什么之前检查其状态:

// Are we in the middle of an animation?
var currentlyAnimating = false;

$('.thumbnail').on('click',function(){
    if (currentlyAnimating) {
        return;
    }

    currentlyAnimating = true;

    $('#imageWrap').append('...');
    $('#imageWrap .active').fadeOut(5500);
    $('#imageWrap .next').fadeIn(4000, function(){
        $('#imageWrap .active').remove();
        $(this).addClass('active');
        currentlyAnimating = false;
    });
});

当然,您也可以通过查询相关元素的DOM或jQuery效果队列的状态来进行此检查,但IMO通过如上所述的本地化解决方案更简单,更清晰。

答案 1 :(得分:1)

您可以使用#imageWrap .next选择器检查#imageWrap .active:animated是否未设置动画。

$('.thumbnail').on('click',function(){
   if(!$("#imageWrap .next, #imageWrap .active").is(":animated")){
      $('#imageWrap').append('<img src="' + $(this).attr('src') + '" class="next" />');
      $('#imageWrap .active').fadeOut(5500);
      $('#imageWrap .next').fadeIn(4000, function(){
          $('#imageWrap .active').remove();
          $(this).addClass('active');
      });//this was missing      
   }
});
相关问题