<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
// var box = document.getElementById('box');
// console.dir(box); // null 代码由上向下执行,此时box元素还未被创建
// BOM onload 页面加载完成之后执行
// 页面加载完成:当页面所有元素创建完成,并且引用的外部资源下载完毕(js、css、图片)
// window.onload = function () { // 可以省略window
onload = function () {
var box = document.getElementById('box');
console.dir(box); // div#box
}
// 页面卸载(关闭)的时候执行
// 刷新页面时console控制台会出现:Blocked alert('hello') during unload.
// 页面卸载的时候window对象会被冻结 所有的对话框都无法使用
// window.onunload = function () {
onunload = function () {
// alert('bye');
console.log('bye'); // 刷新页面时console控制台会出现bye F5:先卸载页面,再重新加载页面
}
</script>
</head>
<body>
<div id="box"> <!-- 标签中也有onload事件 -->
</div>
<script>
// 当前页面上的元素创建完毕就会执行
</script>
</body>
</html>
原生js的onload和onunload
最新推荐文章于 2021-11-16 14:48:32 发布