实时获取网络状态

HTML

<style>
        .tips{
            200px;
            height:40px;
            text-align: center;
            line-height: 40px;
            position: absolute;
            top: 0;
            bottom:0;
            left: 0;
            right: 0;
            margin:auto;
            border-radius: 5px;
            box-shadow: 0 0 2px 2px #000;
            background-color: #333;
            color: #FFF;
            display: none;
        }
</style>
<body>
  <div class="tips"></div>
</body>

javascript

//返回的是当前的网络状态 返回布尔值
//监听的是当前的本地链接
//alert(window.navigator.onLine);

//上面的是一个属性,不能实时去监听当前的网络状态,是我们需要一个事件通知机制,当网络发生变化的时候,以事件实行通知

//通知对话框
var tips = document.querySelector('.tips');

//用户从无网的网络状态被连接时调用
window.addEventListener('online',function(){

    tips.innerHTML = '网络链接正常';
    tips.style.display = 'block';
    setTimeout(function(){
        tips.style.display = 'none';
    },1000);

});


//用户网络从有网到断开时被调用
window.addEventListener('offline',function(){
    tips.innerHTML = '网络链接失败';
    tips.style.display = 'block';
    setTimeout(function(){
        tips.style.display = 'none';
    },1000);
});
原文地址:https://www.cnblogs.com/hynb/p/6037024.html