039-Web前端-JS-文档事件

文档事件
#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();
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值