日期:2014-05-16  浏览次数:20360 次

javascript 判断用户离开当前页面或关闭浏览器并给出提示

<script type="text/javascript">

function closeIt()

{

? return "Any string value here forces a dialog box to \n" +?

? ? ? ? ?"appear before closing the window.";

}

window.onbeforeunload = closeIt;

</script>

或者

<script type="text/javascript">

window.onbeforeunload?= function() {return 'Sure to leave?';};

</script>

可参见:http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx

同一页面可提示可不提示:<html>

<body>

<a href="javascript:alert('Hello World!');">Warning</a><br/>

<a onclick="NoPrompt();" href="http://www.baidu.com">No Warning</a>

<script>// Allow the user to be warned by default.

var allowPrompt = true;

window.onbeforeunload = WarnUser;

function WarnUser()

{

if(allowPrompt)

{

event.returnValue = "You have made changes. They will be lost if you continue.";

}

else

{

// Reset the flag to its default value.

allowPrompt = true;

}