我有一个div "pushBtns"和一个锚标记与id "showPushBtns", "pushBtns"将隐藏在页面加载,并在页面加载后5秒出现。但是,如果用户点击锚id"showPushBtns",它应该停止"timmedshow()"函数,并出现div"pushBtns"。定时显示隐藏功能工作正常,但我无法获得"clearartimeout"的工作。请协助?
p。我是jQuery的初学者。
<script type="text/javascript">
$(document).ready(function() {
var theButtons = $("#pushBtns");
theButtons.hide();
function showIt(){
theButtons.show(1000);
}
function timedShow() {
var timer = setInterval(function() {showIt();},5000);
}
timedShow();
$('#showPushBtns').click(function(){
clearTimeout(timer);
});
});
</script>
回答http://jsfiddle.net/pcvhG/6/
谢谢@mguimard
var theButtons = $("#pushBtns");
var togglBtn = $("#showPushBtns");
var timer;
$(document).ready(function() {
theButtons.hide();
function showIt(){theButtons.show(1000);}
function timedShow() { setTimeout(function() {showIt();},5000);}
timedShow();
$('#showPushBtns').click(function(){clearTimeout(timedShow());showIt()});
});
使用clearInterval
,而不是clearTimeout
。
或者,使用setTimeout
和clearTimeout
,应该更适合您的需要。为什么每5秒调用一次showIt
?
clearTimeout(timer)
只是清除定时器,因此该函数将永远不会运行。因此,您需要在清除计时器后执行showIt()
。
$('#showPushBtns').click(function()
{
clearTimeout(timer);
showIt();
});
编辑:也注意到你正在使用setInterval
。你的意思是用setTimeout
吗?
你的计时器变量是本地的你的timeshow函数-使其成为全局的,你需要使用clearInterval
$(document).ready(function () {
var timer;
var theButtons = $("#pushBtns");
theButtons.hide();
function showIt() {
theButtons.show(1000);
}
function timedShow() {
timer = setInterval(function () {
showIt();
}, 5000);
}
timedShow();
$('#showPushBtns').click(function () {
clearInterval(timer);
});
});
- https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval