扫码关注官方订阅号
<a id="addbtn" class="btn btn-primary">添加</a>
给这个按钮添加一个禁用5秒的限制。使用场景:点击按钮,之后禁用,5秒倒计时,过5秒后才可以再次点击。请问,大侠们,这个场景要怎么写?我在网上找了好几个,不过都有问题,用不了。
人生最曼妙的风景,竟是内心的淡定与从容!
var btn = $('#addbtn'); btn.attr('disabled', 'disabled'); var txt = btn.text(); var count = 5; var func = function() { if (count == 0) { btn.removeAttr('disabled'); btn.text(txt); } else { btn.text(txt + ' (' + count + ')'); count--; setTimeout(func, 1000); } }; setTimeout(func, 1000);
写到按钮的点击事件里。
虽然题主已经采纳了答案。我还是写了一个jquery插件
function CountDown( ele, opt ){ this.opt = $.extend({} , opt || {time:60,before:function(){},after:function(){}}); this.opt.curTime = this.opt.time; this.opt.defaultText = $(ele).html() || $(ele).val(); var _this = this; $(ele).on('click', function(e){ if(_this.opt.curTime !== _this.opt.time){ console.log('qqqq'); e.stopPropagation(); return false; } // before if( _this.opt.curTime === _this.opt.time ){ _this.opt.before.call(ele); } cd.call(this.cd, this); }); function cd( ele ){ var _this = this; if( _this.opt.curTime === 0 ) { _this.opt.curTime = _this.opt.time; _this.opt.after.call(ele); ele.innerHTML = ele.value = _this.opt.defaultText; return; } ele.innerHTML = ele.value = '倒计时('+(_this.opt.curTime--)+')'; setTimeout(function(){ cd.call(_this, ele); }, 1000); } } $.extend($.fn,{ 'countDown': function( opt ){ return this.each(function(){ if(!this.cd){ this.cd = new CountDown(this, opt); } }); } });
测试代码:
<a href="javascript:;">超链接</a> <button>按钮</button> <input type="button" value="input"> <p>p标签</p> $('a,button,input').countDown({ time: 10, before: function(){ console.log(this.nodeName+': 开始倒计时') }, after: function(){ console.log(this.nodeName+': 结束倒计时') } }); $('p').countDown({ time: 5, before: function(){ console.log(this.nodeName+': 开始倒计时') }, after: function(){ console.log(this.nodeName+': 结束倒计时') } });
完整demo https://jsfiddle.net/scroller/vLotyroo/
就是js实现定时器功能。 建议楼主多看看setTimeout和setInterval的用法
var f = true; 点击事件{ if (f) { f = false; // 可以加上冷却时间的效果提示 //执行语句 //setTimeout 5秒后 f = true } }
就是这么简单粗暴有效!
setTimeout
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
写到按钮的点击事件里。
虽然题主已经采纳了答案。我还是写了一个jquery插件
测试代码:
完整demo https://jsfiddle.net/scroller/vLotyroo/
就是js实现定时器功能。 建议楼主多看看setTimeout和setInterval的用法
就是这么简单粗暴有效!
setTimeout