问题情境:在调用浏览器打印功能方法window.print()后,页面出现错乱进而使用window.document.body.innerHTML替换页面进行解决从而出现事件丢失问题。
代码片段:
let bdhtml = window.document.body.innerHTML;
window.print(); //调用浏览器的打印功能
window.document.body.innerHTML = bdhtml; // 最后还原页面
问题分析:MDN 链接有这句,会移除元素的所有子元素
Setting the value of
innerHTML
removes all of the element's descendants and replaces them with nodes constructed by parsing the HTML given in the stringhtmlString
解决方法:
1.利用事件代理,全部委托给document,然后通过targe确定事件源
2.统一管理监听事件注销
3.使用location.reload()当前页面刷新
最终代码:
let bdhtml = window.document.body.innerHTML;
window.print(); //调用浏览器的打印功能打印指定区域
window.document.body.innerHTML = bdhtml; // 最后还原页面
location.reload(); // 刷新页面