【问题标题】:jquery count hover eventjquery计数悬停事件
【发布时间】:2011-05-12 07:18:39
【问题描述】:

我想计算多少时间,我将鼠标悬停在一个 html 元素上。

例如

链接

<a class="mylink">Check me Out !</a>

jquery

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

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

提前致谢!

【问题讨论】:

  • 是的,;) jquery 更像...法语! :p
  • 在第二次阅读时,您能否澄清一下您是要计算在元素上悬停的次数,还是要在元素上悬停的时间长度?

标签: jquery events hover


【解决方案1】:

如果您想为每个匹配的元素保留一个单独的计数器,请执行以下操作:

jquery('.mylink').mouseover(function(){
    var $this = $(this);
    var count = parseInt($this.data('count'), 10) + 1;
    $this.data('count', count);
});

然后您可以使用$(selector).data('count') 获取每个元素的计数。

编辑:修正愚蠢的错误。

【讨论】:

  • +1 干净整洁的解决方案。也许我很笨,但你没有忘记每次都将1添加到计数中吗?
  • 大声笑,2 次投票,4 小时后,有人注意到了。谢谢。:)
【解决方案2】:
$(function()
{
    var myCounter = 0;
    $('.mylink').mouseover(function()
    {
        myCounter++;
    });
});

【讨论】:

    【解决方案3】:

    如果你想知道你在一个元素上悬停了多少秒,试试这个:

    $('.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 ) );
        }
    );
    

    【讨论】:

      【解决方案4】:

      调用这个函数...

      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);
       }
      
      } 
      

      【讨论】:

        猜你喜欢
        • 2011-08-24
        • 2010-09-30
        • 1970-01-01
        • 2014-01-07
        • 1970-01-01
        • 2016-01-28
        • 2011-03-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多