在mousdown down延迟之后防止链接事件

时间:2012-09-16 21:42:50

标签: javascript jquery

我正在处理一个函数,以便当用户点击并保留链接时,该链接不会将用户发送到相应的链接。但是,我使用的功能不起作用。我想要的是用户点击一个链接,如果他们按住它超过一秒钟,该链接将不再有效,并且不会触发任何事件。经过一段时间的浏览,我找不到代码的错误。所以我的问题是,我做错了什么? http://jsfiddle.net/rQP6g/2/

<a href="www.google.com" >link</a>

<script>
var timeoutId = 0;
    $('a').mouseup(function() {
    timeoutId = setTimeout(function(e) {  
    e.preventDefault();
e.stopPropagation();
}, 1000);
}).bind('mouseup', function() {
clearTimeout(timeoutId);
});
</script>

3 个答案:

答案 0 :(得分:6)

这应该有效:http://jsfiddle.net/rQP6g/18/

JS如下所示:

var mousedownTime;

$('a').mousedown(function(e) {
    mousedownTime = new Date();
}).click(function(e) {
    // If the mouse has been hold down for more than 1000 milliseconds ( 1 sec. ), cancel the click
    if(Math.abs(new Date() - mousedownTime) > 1000)
        e.preventDefault();
});​

基本思想是捕捉按下鼠标按钮的时间 - 然后,当释放时,点击事件被触发,并且如果超过1秒则计算它。自链接被按下以来已经过去了。如果是这种情况,则取消单击事件并且不会加载链接:)

答案 1 :(得分:1)

以下是您的回答:http://jsfiddle.net/rQP6g/19/经过测试和运作

您的jQuery代码:

var startingTime, timeOut = 1000;
(function($) {
    $('a').bind('click', function(e) {
        e.preventDefault();
    }).bind('mousedown', function(e) {
        window.startingTime = +new Date();
    }).bind('mouseup', function (e) {
        console.log('Starting time: '+ window.startingTime);
        var currentTime = +new Date();
        console.log('Current time: '+ (+new Date()));
        var difference = currentTime - window.startingTime;
        console.log (difference);
        if (difference > timeOut) {
            console.log('You are too slow, nothing happens');
        } else {
            console.log($(this).attr('href'));
            window.location.href = $(this).attr('href');
        }
    });
})(jQuery);

答案 2 :(得分:1)

我会采用相反的方法 - 阻止所有事情,然后允许在阈值之前释放点击次数:

// set threshold in millisecs:
var threshold = 1000;

$('a').on('click',function(event){

    event.preventDefault();

    // inject current time in link element:
    $(this).attr('data-timestamp', new Date.getTime());

}, function(event){

    // check mousedown timestamp against mouseup timestamp:
    if( (new Date.getTime() - $(this).attr('data-timestamp') < threshold){

        window.location.href = $(this).attr('href');    

    }

});​​​​