jQuery计算鼠标悬停事件

3
我希望能够计算我在HTML元素上悬停的时间。 例如: 链接
<a class="mylink">Check me Out !</a>

jquery

jQuery('.mylink').hover(function(){

//what should i do here to count
});

提前感谢你!


是的,;) jQuery 更像是……法国人!:p - Roko C. Buljan
2
在第二次阅读时,请澄清一下您是想计算您悬停在元素上的次数,还是获取您悬停在该元素上的时间长度? - DarthJDG
4个回答

6
如果您想为每个匹配元素保留单独的计数器,请按照以下步骤操作:
jquery('.mylink').mouseover(function(){
    var $this = $(this);
    var count = parseInt($this.data('count'), 10) + 1;
    $this.data('count', count);
});

然后你可以使用$(selector).data('count')获取每个元素的计数。
编辑:修复了愚蠢的错误。

1
+1 个简洁明了的解决方案。也许我很蠢,但是你忘记每次将 1 添加到计数器了吗? - kapa
哈哈,2个赞和4个小时后,有人注意到了它。谢谢 :) - DarthJDG

4
$(function()
{
    var myCounter = 0;
    $('.mylink').mouseover(function()
    {
        myCounter++;
    });
});

1
如果你想知道你在一个元素上悬停了多少秒,可以尝试这个方法:
$('.mylink').hover(
    //mouseover handler
    function(){
        //record the current time
        $(this).data( 'start', new Date().getTime() );
    },
    //mouseout handler
    function(){
        //grab the end time
        var end = new Date().getTime();
        //calculate the difference in seconds
        var hoverTime = ( end - $(this).data('start') )/1000;
        //use the result
        alert( hoverTime.toFixed( 2 ) );
    }
);

0

调用这个函数...

jquery('.mylink').hover(function(){

start(true)
});


function start(isStarted, index){
if(!index){
 index = 0;
 }

 if(isStarted) {
 started[index] = true;
 counter[index] =0;

 }


if(started[index] && true) {
 counter[index] += 1;
 timer = setTimeout("start(false," + index + ")",1000);
 }

} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接