2016-02-09 24 views
-2

通常情況下,我們可以使用防止F5刷新頁面與javascript如下如何防止F5當光標在URL

if (keyCode == 116) 
    event.preventDefault(); 

但我想,以防止F5刷新,從工作時,光標在URL。這不是應用程序刷新,而是刷新頁內瀏覽器。 當光標位於URL上並且用戶按下F5鍵時,頁面將刷新。我需要防止這一點。

請幫幫我。

回答

1

你不能防止這種情況發生。一旦頁面上的焦點丟失(即當您點擊URL欄時),javascript將不再接收鍵盤事件。

但是,您可以向用戶顯示一條消息,以警告他們即將離開該頁面。

window.onbeforeunload = function(){ 
    return "Your message here"; 
}; 

,當他們試圖離開頁面(或刷新它),可以選擇離開或留在網頁上的用戶將被提示消息。你不能完全阻止用戶重新加載,但如果他們這樣做,你可以讓它聽起來真的很可怕。

0

,如果你的光標在位置不能檢查,如果鼠標光標如果在URL,但你可以檢查[0,0]

var cursorX; 
var cursorY; 
document.onmousemove = function(e){ 
    cursorX = e.pageX; 
    cursorY = e.pageY; 
} 

$(document).on("keydown", function(e){ 
    if ((e.which || e.keyCode) == 116 && (cursorX == 0 && cursorY == 0)) 
     e.preventDefault(); 
}); 

如果cursorX和粗略等於0,則防止您的行動

+0

你,我們可以得到的位置,但是,如何阻止瀏覽器刷新 – Srikanth

+0

@Srikanth編輯我的回答 – Gwendal

+0

你的代碼執行時,光標在我們的應用程序,但我會繼續URL鼠標光標,點擊F5然後將頁刷新,其瀏覽器功能。我希望你得到了我要告訴的 – Srikanth

0

您可以使用的onmouseover跟蹤,當鼠標移動到URL,然後你可以使用的onmouseout跟蹤時它是關閉的URL。看下面的例子。

<a onmouseover="overIsTrue()" 
    onmouseout="overIsFalse() href="http://www.yourpage.com">here</a> 

//keep track of the mouse state 
var overURL = false; 

window.addEventListener('keydown', function (event) { 

    // if the key is 116 and the mouseover is true 
    if (event.keyCode === 116 && overURL) { 

     // prevent default behaviour 
     event.preventDefault(); 

     return false; 
    } 

}); 

//mouse over is true 
function overIsTrue() { 
    overURL = true; 
} 

//mouse over is false 
function overIsFalse() { 
    overURL = false; 
} 
+0

我不想鼠標或鼠標懸停。當我的鼠標專注於URL,如果我點擊F5,那麼通常頁面將刷新。這我想阻止。它的瀏覽器功能。 – Srikanth

+0

你是說你想在用戶通過瀏覽器的URL欄時禁用F5頁面刷新?或者當他們仍然在您的頁面上並且鼠標懸停在鏈接上時是否要禁用F5? – Tim