背景:之前做了一个功能用户用户一定时间不操作自动退出,是通过记录用户点击菜单的时间,和当前时间比对的,这样只能监控到菜单点击;多数情况用户是在填写表单,突然给退出了,用户反馈非常不友好,需要我们优化。
经过网上查阅资料发现可以通过js来监听用户的输入和鼠标移动,页面上来用定时器控制超时,超时后调注销登录方法,即可完美解决。
实现方式:在页面主框架里面加入监听代码,超时后调用注销方法即可。
代码如下:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UAT-8" />
<title>无标题文档</title>
<SCRIPT language="JavaScript">
var timerIdle=0;//定义空闲时间,单位秒
var timerBusy=0;//定义倒计时开始,单位秒
var timerIdle1=5;//定义超时时间,单位秒
var timerBusy1=10;//定义超时提醒后退出时间,单位秒
//初始化信息-这里只是为做示例,实际情况不用如此
function timerTimeout(){
timerIdle++;
if (timerIdle>timerIdle1){
if (timerBusy==0){
timerBusy=timerBusy1+1;
//显示倒计时
document.getElementById("timerUI").style.display="inline";
}
timerBusy--;
//显示倒计时效果
document.getElementById("_timerBusy").innerHTML=timerBusy;
//判定超时,停止计时
if (timerBusy<=0){
timerExit();
return;
}
}else{
timerBusy=0;
}
//计时器
window.setTimeout("timerTimeout()",1000);
}
//隐藏div,这里只是为做示例,实际情况不用如此
function timerUser(){
timerIdle=0;
document.getElementById("timerUI").style.display="none";
}
//超时处理方法
function timerExit(){
//超时处理.这里可以写注销登录方法
alert("已经退出系统了~~");
document.getElementById("outTimeDiv").style.display="inline";
timerUser();
}
//启动计时器方法
window.setTimeout("timerTimeout()",1000);
/******************事件监听***************************/
function mouseMove(ev){
ev= ev || window.event;
timerUser();
var mousePos = mouseCoords(ev);
}
function mouseCoords(ev){
if(ev.pageX || ev.pageY){
return {x:ev.pageX, y:ev.pageY};
}
return {
x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY + document.body.scrollTop - document.body.clientTop
};
}
document.onmousemove = mouseMove;
document.onkeydown = mouseMove;
</SCRIPT>
</head>
<body>
<div>--------------------js监听用户操作超时后退出系统----------------------</div>
<DIV ID="timerUI" style="position:absolute; left:30px; top:30px; font-size:20px;display:none">
<table width="300" border="0" cellspacing="0" cellpadding="0">
<tr>
<td nowrap align="right" ID="_timerBusy" style=" font-size:36px; font-weight:bold; color:#FF0000;"></td>
<td nowrap align="left">您长时间不没有操作,系统将 秒后将退出</td>
</tr>
<tr>
<td nowrap align="right"></td>
<td nowrap align="right"></td>
<td nowrap align="left"> 如继续操作点任意键即可</td>
</tr>
</table>
</DIV>
<div ID="outTimeDiv" style="position:absolute; left:30px; top:30px; font-size:20px;display:none"> 系统检测到您长时间未进行任何操作,为保护您的信息安全已经自动退出</div>
</body>
</html>
示例效果图: