<!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <title>html5 js 监听网络在线与离线</title> </head> <body> <div id="status" style="font-size:100px;"></div> </body> </html> <script type="text/javascript" language="javascript" charset="utf-8"> $$ = function(id){return document.getElementById(id);}; if(navigator.onLine){ $$("status").innerHTML="第一次加载时在线"; } else{ $$("status").innerHTML="第一次加载时离线"; } window.addEventListener("online", online, false); function online(){ $$("status").innerHTML="on"; } window.addEventListener("offline", offline, false); function offline(){ $$("status").innerHTML="off"; } </script>
<!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <title>html5 js 监听网络在线与离线</title> <style type="text/css"> #status { position : fixed; 100%; font : bold 1em sans-serif; color: #FFF: padding : 0.5em } #log { padding: 2.5em 0.5em 0.5em; font: 1em sans-serif; } .online { background: green; } .offline { background: red; } </style> </head> <body> <div id="status" style="font-size:100px;"> <div id="status"></div> <div id="log"></div> <p>This is a test</p> </div> </body> </html> <script type="text/javascript" language="javascript" charset="utf-8"> window.addEventListener('load', function() { var status = document.getElementById("status"); function updateOnlineStatus(event) { var condition = navigator.onLine ? "online" : "offline"; //alert(condition); status.className = condition; status.innerHTML = condition.toUpperCase(); log.insertAdjacentHTML("beforeend", "Event: " + event.type + "; Status: " + condition); } window.addEventListener('online', updateOnlineStatus); window.addEventListener('offline', updateOnlineStatus); //alert(navigator.onLine); //updateOnlineStatus(); }); </script>