【发布时间】:2019-03-25 23:42:32
【问题描述】:
单击 div 会发生一些事情,并且我会从 div 中删除类,因此如果我再次单击 div 不会发生任何事情。但是虽然类不在了,但是下一次点击启动也是一个jQuery函数。
我想要一个按钮点击然后发生:
- 一个。一个 div 将在 x 秒后隐藏
- 乙。另一个 div 将在 x 之后显示 秒
- c。倒计时会显示更改发生的时间
那会很好用。
如果我首先单击 button1,倒计时应该开始(确实如此)。
如果我再次单击按钮 1,倒计时不应再次开始。
(但确实如此 - 尽管我在第一次单击时删除了选择器类)
如何避免倒计时再次开始?
$('.button1').click(function() {
$('.output0').delay(10000).fadeOut(500);
$('.output1').delay(10500).show(0);
});
$('.button1').click(function() {
$('.button1').removeClass('button1');
});
(function($) {
$.fn.countTo = function(options) {
// merge the default plugin settings with the custom options
options = $.extend({}, $.fn.countTo.defaults, options || {});
// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(options.speed / options.refreshInterval),
increment = (options.to - options.from) / loops;
return $(this).each(function() {
var _this = this,
loopCount = 0,
value = options.from,
interval = setInterval(updateTimer, options.refreshInterval);
function updateTimer() {
value += increment;
loopCount++;
$(_this).html(value.toFixed(options.decimals));
if (typeof(options.onUpdate) == 'function') {
options.onUpdate.call(_this, value);
}
if (loopCount >= loops) {
clearInterval(interval);
value = options.to;
if (typeof(options.onComplete) == 'function') {
options.onComplete.call(_this, value);
}
}
}
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 100, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
onUpdate: null, // callback method for every time the element is updated,
onComplete: null, // callback method for when the element finishes updating
};
})(jQuery);
$('.button1').click(function() {
jQuery(function($) {
$('.timer').countTo({
from: 10,
to: 0,
speed: 10000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
});
});
.button {
padding: 30px;
background-color: red;
width: 200px;
}
.output0 {
padding: 30px;
background-color: yellow;
width: 200px;
}
.output1 {
padding: 30px;
background-color: green;
width: 200px;
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="button1 button" style="">
Button1 to show something after 10 seconds
</div>
<div class="output0" style="">
I will hide after 10 seconds
</div>
<div class="output1" style="">
I will show after 10 seconds
</div>
<div class="timer"></div>
【问题讨论】: