我有一些简单的淡入淡出功能,可触发div的淡入/淡出。但是,如果您通过垃圾邮件单击按钮,它们都将开始运行并且看起来很糟糕。我想要的是仅在当前未运行任何功能时才触发该功能。
$('.a').click(function(){
$('#about, #contact').fadeOut(500);
$('#welcome').delay(500).fadeIn(500);
})
$('.b').click(function(){
$('#welcome, #contact').fadeOut(500);
$('#about').delay(500).fadeIn(500);
})
$('.c').click(function(){
$('#about, #welcome').fadeOut(500);
$('#contact').delay(500).fadeIn(500);
})
答案 0 :(得分:1)
您可以在变量中以及在褪色检查状态之前存储元素的褪色状态。在这种情况下,我添加了running
变量。
var running = false;
$('.a').click(function(){
if (!running){
running = true;
$('#about, #contact').fadeOut(500);
$('#welcome').delay(500).fadeIn(500, function(){
running = false;
});
}
})
$('.b').click(function(){
if (!running){
running = true;
$('#welcome, #contact').fadeOut(500);
$('#about').delay(500).fadeIn(500, function(){
running = false;
});
}
})
$('.c').click(function(){
if (!running){
running = true;
$('#about, #welcome').fadeOut(500);
$('#contact').delay(500).fadeIn(500, function(){
running = false;
});
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="a">aaa</div>
<div class="b">bbb</div>
<div class="c">ccc</div>
<div id="welcome">welcome</div>
<div id="about">about</div>
<div id="contact">contact</div>
您还可以简化代码,如底部所示
var running = false;
$('.button').find('.a, .b, .c').click(function(){
if (!running){
running = true;
var dataChild = $(this).data("child");
$(".child *:not(#"+dataChild+")").fadeOut(500);
$("#"+dataChild).delay(500).fadeIn(500, function(){
running = false;
});
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="button">
<div class="a" data-child="welcome">aaa</div>
<div class="b" data-child="about">bbb</div>
<div class="c" data-child="contact">ccc</div>
</div>
<div class="child">
<div id="welcome">welcome</div>
<div id="about">about</div>
<div id="contact">contact</div>
</div>