2011-03-22 154 views
3

有一种称为duell的技术,它用于网站的可访问性原因。它只用于只能移动设备的人(即鼠标),并且可以像这样工作。在悬停效果悬停持续时间比以秒为例1秒时触发点击功能。我想用jQuery来模拟我的HTML中的按钮元素。如何在HTML按钮短暂延迟后触发点击?

回答

6
(function() { 
    var clearTimeout = function(b) { 
     window.clearTimeout($(b).data("hoverTimer")); 
    } 
    $("button").hover(function() { 
     var button = $(this); 
     button.data("hoverTimer", window.setTimeout(function() { 
     button.trigger("click"); 
     }, 1000)); 
    }, function() { 
     clearTimeout(this) 
    }).click(function() { 
     clearTimeout(this) 
    }); 
})(); 

编辑以避免多次点击。 (谢谢,Alnitak)

+1

但可能会导致多个触发器,如果​​按钮被实际点击... – Alnitak 2011-03-22 10:59:47

9
var timer = null; 
$('button').hover(mouseIn, mouseOut); 

function mouseIn() { 
    timer = setTimeout(triggerClick, 3000); 
} 

function mouseOut() { 
    clearTimeout(timer); 
} 

function triggerClick() { 
    $('button').trigger('click'); 
} 

此解决方案使用计时器。当您将鼠标悬停在元素上时启动计时器,并在停止时将其清除。显然这只适用于1个按钮,但您可以轻松修改它以适用于页面上的所有按钮。

5

我敲出了一个快速的jQuery插件来做你所问的。在http://jsfiddle.net/raybellis/tF833/

源(和演示)作为参考这里,(当前)的代码如下所示:

(function($) { 

    $.fn.duell = function() { 
     return this.each(function() { 
      var timer = null; 
      var el = this; 
      var stopTimer = function() { 
       if (timer) { 
        clearTimeout(timer); 
        timer = null; 
       } 
      }; 

      var startTimer = function() { 
       stopTimer(); 
       timer = setTimeout(function() { 
        $(el).click(); 
       }, 1000); 
      }; 

      // make sure other clicks turn off the timer too 
      $(el).click(stopTimer); 

      // handle mouseenter, mouseleave 
      $(el).hover(startTimer, stopTimer); 
     }); 
    }; 
})(jQuery); 
+0

不对我的第一个插件不利,尽管它在边缘是一个小小的粗糙:)对于奖励点,超时应该是可配置的,并且当模拟点击发生时会有视觉反馈。 – Alnitak 2011-03-22 10:48:20