文档事件
#6.22
文档事件中主要是指添加给整个文档的事件。在这一类事件中,绝大部分并不需要用户主动去进行调用。而是通过文档的不同状态来进行自动执行。
(1)加载成功\失败事件:load\error
(2)当DOM加载完成时触发事件:DOMContentLoaded
(3)页面(文档)发生卸载时触发的事件:beforeunload
(4)文档加载状态判断事件:readystatechange
(5)文档大小发生改变时的回调事件:resize
DOM文档加载的步骤为:
解析HTML结构。
加载外部脚本和样式表文件。
解析并执行脚本代码。
DOM树构建完成。 //DOMContentLoaded执行
加载图片等外部文件。
页面加载完毕。 //load执行
1.加载成功/失败事件
document.querySelector('img').onload=function(){ //onerror
console.log('图片加载失败');
}
2.页面(文档)发生卸载时触发的事件:beforeunload //了解,少用
window.onbeforeunload = function () {
return '确定要离开';
};
3.页面加载状态判断
console.log(document.readyState); document.addEventListener('readystatechange',function(){
console.log('文档加载状态变化:'+document.readyState);
});
4.DOM是否加载完成
document.addEventListener('DOMContentLoaded',function(){
console.log('文档DOM树构建完成');
});
window.onload=function(){ //页面彻底加载完成时触发(window)
console.log('文档彻底加载完成');
};
document.querySelector('img').onload=function(){
console.log('图片加载完成');
}
5.文档大小发生改变时的回调事件:resize //了解 若不用延迟判定会多次调用
window.onresize = function(){ console.log('width:'+document.documentElement.clientWidth); console.log('height:'+document.documentElement.clientHeight);
};
若不设定延迟时间, 每次更改尺寸其实会不停执行
//优化的延迟判定
window.onresize = function(){ console.log('width:'+document.documentElement.clientWidth); console.log('height:'+document.documentElement.clientHeight);
};
var flag = true;
function fra(){
if(flag){ console.log('width:'+document.documentElement.clientWidth); console.log('height:'+document.documentElement.clientHeight);
console.log('---------------------');
flag = false;
setTimeout(function(){flag = true;},500);
}
}
window.onresize = function(){
fra();
};