<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>检测浏览器是否在线</title>
</head>
<body>
<input type="button" id="jc" name="online&offline" value="检测浏览器是否在线">
<p>This is a paragraph</p>
<script type="text/javascript">
function addHandler(element, type, handler){
if (element.addEventListener){
element.addEventListener(type, handler, false);
} else if (element.attachEvent){
element.attachEvent("on" + type, handler);
} else {
element["on" + type] = handler;
}
}
function line(){
if (navigator.onLine) {
console.log("online");
}else{
console.log("offline");
}
}
var ipt=document.getElementById("jc");
addHandler(ipt,"click",line);//IE6-8也行
//为了更好地确定网络连接是否可用,HTML5还为我们定义了两个事件:online和offline。
//使用window.onOnline和window.onOffline事件, 监听浏览器的联网状态
window.addEventListener("online", function(e){
console.log("浏览器连上了网络");//断了再连上会console.log
});//IE6-8下addEventListener没用
window.addEventListener("offline", function(e){
console.log("浏览器未连上了网络");//掉线的时候会console.log
});
</script>
</body>
</html>
检测浏览器是否在线
最新推荐文章于 2024-07-05 15:21:58 发布