【发布时间】:2015-11-05 11:53:40
【问题描述】:
这应该很容易,但我无法让它正常工作......我有一个 div 元素用作按钮。我不希望按钮一直可见,只是在用户触摸屏幕(用手指或鼠标)时出现,在不活动后保持可见一段时间(比如 2 秒)然后消失。
我不希望它在可见后 2 秒消失(因为我可以使用 jQuery 延迟),我希望它在用户停止与屏幕交互后 2 秒消失(即 #grid 元素在我的情况下)。只要用户触摸屏幕或移动鼠标,按钮就可见,当他停止该活动 2 秒后,按钮就会消失。
以下我有,它不起作用:
var grid = $('#grid');
grid.bind('mousemove touchmove tap swipeleft swipeup swipedown swiperight', function(e) {
var timer;
var circle= $('.circle-button');
if (!circle.is(":visible")) {
//button is not visible, fade in and tell it to fade out after 2s
$('.circle-button').fadeIn('slow');
timer = setTimeout(function(){ $('.circle-button').fadeOut('slow') }, 2000);
}
else {
//button is visible, need to increase timeout to 2s from now
if (timer) clearTimeout(timer);
timer = setTimeout(function(){ $('.circle-button').fadeOut('slow') }, 2000);
}
});
即使上述方法可行,对我来说似乎效率很低,为每个 mousemove 重新启动一个计时器(虽然不确定这是一个真正的问题)。如果有人可以帮助我提供一个有效的、合理有效的解决方案,将不胜感激。 干杯!
--- 编辑 ----- 谢谢大家的回复,都很好。我最终在下面使用了 Rohan Veer 的建议,因为这对我来说似乎是最优雅的解决方案,不必在每次鼠标移动时重新启动计时器。
【问题讨论】:
-
首先,使用
.on()insted of.bind()- 这是首选方法
标签: javascript jquery html timer settimeout