2016-02-09 27 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