2012-10-17 50 views
4

这是我当前的代码如何在两秒钟的悬停后执行一项功能?

google.maps.event.addListener(marker, `mouseover`, function() { 
    alert('loaded when i hovered'); 
}); 

,但我想如果鼠标超过两秒钟元素要执行的功能。

我试过这个,但没有奏效。

google.maps.event.addListener(marker, `mouseover 2000`, function() { 
    alert('loaded after then when i stay mouse 2 sec'); 
}); 

我需要做什么才能使该功能在两秒钟后悬停?

+0

请重播我的例子。谢谢 – Dest

回答

6

您需要使用计时器。在mouseover中设置它,然后在定时器回调中做你的工作;您还需要处理停止计时器的鼠标事件。

var timeoutId = null; 
google.maps.event.addListener(marker, 'mouseover',function() { 
    timeoutId = window.setTimeout(function(){ 
    alert("I did it!"); 
    }, 2000); 
}); 

// Cancel your action if mouse moved out within 2 sec 
google.maps.event.addListener(marker, 'mouseout',function() { 
    window.clearTimeout(timeoutId) 
}); 
0

在mouseover事件中调用setTimeout。将返回值存储在共享的地方(例如,在关闭中)。

在mouseout事件中调用clearTimeout。如果该事件在两秒钟之前没有触发,则传递给setTimeout的功能将被调用。

+1

谢谢你的回答,你能举个例子吗? – Dest

3

这将是这样的,使用setTimeout

var timer; 

google.maps.event.addListener(marker, 'mouseover', function() {   
    timer = window.setTimeout(function(){ 
    alert("Stackoverflow Rocks!!!"); 
    }, 2000); 
}); 

google.maps.event.addListener(marker, 'mouseout', function() {   
    window.clearTimeout(timer); 
}); 
相关问题