2011-10-10 27 views
0

是否有可能使用jQuery'time'光標懸停在某個元素上的時間?如果有人能讓我朝正確的方向發展,那將會很好。如何檢查你懸停元素的時間長度

泰斯

+1

重複回答有http://stackoverflow.com/questions/5974617/jquery-count-hover-event –

+0

對不起,沒有看到帖子 – Thijs

回答

3

我這樣做是使用jQuery的.hover() - 你基本上可以存儲在元素的.data開始時間,並將其與Date().getTime()當鼠標離開。

敲起來這裏的工作小提琴:http://jsfiddle.net/XQ9kY/1/

的HTML:

<div id="hoverZone" class="hoverable"> 
    You can hover over me<br />for as long as you like 
</div> 
<div id="hoverResult"> 
</div> 

jQuery的:

$('.hoverable').hover( 
    function(){  
     $(this).data('inTime', new Date().getTime()); 
    },  
    function(){  
     var outTime = new Date().getTime();  
     var hoverTime = (outTime - $(this).data('inTime'))/1000;   
     $('#hoverResult').html('you were hovering for ' + hoverTime + 's'); 
    } 
); 
+0

非常感謝! – Thijs

4

您可以使用懸停功能來做到這一點。事情是這樣的:

$(document).ready(function() { 
    $('#myElement').hover(
     function() { 
      $(this).data("hoverStart", (new Date()).getTime()); 
     }, 
     function() { 
      var hoverTime = ((new Date()).getTime() - $(this).data("hoverStart"))/1000; 

      alert("You hovered for " + hoverTime + " seconds."); 
     } 
    ); 
});