使用JavaScript在离开页面前通过onbeforeunload判断并提示用户

作者:闭包旅人

时间:2026-10-28

浏览:652

本文介绍如何在HTML页面中使用JavaScript的onbeforeunload事件,在用户尝试关闭或离开当前页面前进行条件判断。通过获取特定输入框的值,若为空则弹出确认对话框,防止用户误操作离开页面。

</html>

具体实现代码如下所示:

 
JavaScript离开页面提示实现代码<!doctype html>
<html lang="cn">
<head>
<meta charset="UTF-8">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>js离开当前页面前判断条件提示是否要离开页面</title>
<script type="text/javascript">
window.onbeforeunload = function() {
{ 
var unloads = document.getElementById("unloads").value;
if(unloads == null || unloads == "") {
return "您确定要退出页面吗?";
} 
} 
}
</script>
</head>
<body>
<input type="text" id="unloads" name="unloads" value="" />
</body>

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章