H5新增了 online 和 offline 两个事件;
online是在网络连接时被调用,
offline是在网络断开时被调用。
监听对象都是window。
以下是演示代码(博主引用:bootstra),没有的大家可以自己写个css样式。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="../ku/css/bootstrap.min.css">
</head>
<body>
<style>
.bg-danger {
display: none;
}
</style>
<div class="title bg-success text-center text-white p-4"></div>
<div class="title bg-danger text-center text-white p-4"></div>
<script>
window.addEventListener('online', function () {
document.querySelector('.bg-success').style['display'] = 'block';
document.querySelector('.bg-danger').style['display'] = 'none';
document.querySelector('.bg-success').innerHTML = '有网';
})
window.addEventListener('offline', function () {
document.querySelector('.bg-success').style['display'] = 'none';
document.querySelector('.bg-danger').style['display'] = 'block';
document.querySelector('.bg-danger').innerHTML = '没网';
})
</script>
</body>
</html>
当有网络连接时:
当网络断开时:
可以按f12调出浏览器的窗口,并找出下面的标签,可以手动模拟网络连接状态,不用真的去拔网线。
以上便是我的学习中用到的知识点,如果有错误的地方,请别骂我,可以告诉我,一起学习❥(^_-)