2012-09-16 21 views
0

我正在研究一個函數,以便當用戶單擊並保留鏈接時,鏈接不會將用戶發送到相應的鏈接。但是,我使用的功能不起作用。我想要的是用戶點擊一個鏈接,如果他們按住一秒以上,鏈接不再起作用,也不會觸發任何事件。經過一段時間的瀏覽之後,我找不到代碼出了什麼問題。所以我的問題是,我做錯了什麼? http://jsfiddle.net/rQP6g/2/mousdown down之後阻止鏈接事件延遲

<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> 
+1

我不確定我是否理解您正在嘗試執行的操作。鏈接通常在'click'時激活,而不是在'mousedown'上,所以'preventDefault'不會有幫助。您是否試圖做到這一點,因此用戶必須按住按鈕一秒才能使鏈接實際工作,但不能爲縮短點擊時間做任何事情。您描述的行爲至少是我的默認設置,我可以整天按住鼠標按鈕,而不是按照鏈接。 –

+0

對不起,我感到困惑。我只需要按住鏈接,並在一兩秒之後,當我執行'mouseup'時,鏈接就是'preventDefault'。 – jason328

+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秒則被計算。自鏈接被按下以來已過去。如果是這樣的情況下,點擊事件被取消和鏈接將不會加載:)

+0

這對於併發問題並不安全。 –

+2

@MattWhipple請你詳細說明一下嗎? –

+0

每次點擊鏈接都會初始化mouseDownTime。如果我之後點擊任何鏈接,它將被停用。所以一個鏈接將禁用整個鏈接頁面。 –

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

    } 

});​​​​