这应该很容易,但我不能让它工作,因为它应该......我有一个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);
}
});
即使以上情况有效,对我来说似乎也非常无效,为每个鼠标移动重新启动计时器(不确定这是一个真正的问题)。如果有人可以帮助我提供一个有效且合理有效的解决方案,那将非常感激。 干杯!
---编辑----- 感谢回复,他们都很好。我最终使用了Rohan Veer的建议,因为它似乎是我最优雅的解决方案,不需要在每次鼠标移动时重新启动计时器。
答案 0 :(得分:1)
试试这个 -
<script type="text/javascript">
var idleTime = 0;
$(document).ready(function () {
//Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 60000); // 1 minute
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 2) { // 2 minutes
// fade out div
}
}
</script>
答案 1 :(得分:0)
您的代码似乎非常接近一个有效的解决方案,我只进行了一些微小的改动。几乎唯一的方法是在每次移动时设置一个计时器,但也清除之前的计时器。
以下代码根据您的说明运作。
var timer;
var grid = $('#grid');
grid.bind('mousemove touchmove tap swipeleft swipeup swipedown swiperight', function(e) {
var circle= $('.circle-button');
if (timer) clearTimeout(timer);
if (!circle.is(":visible")) {
circle.fadeIn('slow');
}
timer = setTimeout(function(){ circle.fadeOut('slow') }, 2000);
});
&#13;
#grid{
width:200px;
height: 100px;
border: 1px solid black
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="grid"></div>
<button class="circle-button">A button</button>
&#13;
答案 2 :(得分:0)
您可以设置所需时间和超时时间,将其隐藏。以下是Reference JSFiddle。
var interval = null;
function initInterval(){
if(interval)
clear();
showElement();
interval = setTimeout(function(){
$(".btn").fadeOut();
clear();
},2000);
}
function clear(){
window.clearInterval(interval);
interval = null;
}
function showElement(){
$(".btn").fadeIn();
}
function registerEvents(){
console.log("Events registering");
$(document).on("mousemove", function(){
initInterval();
});
}
(function(){
registerEvents();
})()
.btn{
width:200px;
background:blue;
color:#fff;
padding:5px;
text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="btn">Will hide in 2 secs</div>