微信扫一扫打赏支持

js触发页面resize事件

js触发页面resize事件

一、总结

一句话总结:

1、let myEvent = new Event('resize');
2、window.dispatchEvent(myEvent);

 

 

 

二、js触发页面resize事件

博客对应课程的视频位置:

 

1、createEvent + dispatchEvent

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8">
 5         <title>js触发页面resize</title>
 6     </head>
 7     <body>
 8         <script>
 9             window.onresize = function() {
10                 alert('触发成功');
11             };
12 
13             if(document.createEvent) {
14                 var event = document.createEvent("HTMLEvents");
15                 event.initEvent("resize", true, true);
16                 window.dispatchEvent(event);
17             } else if(document.createEventObject) {
18                 window.fireEvent("onresize");
19             }
20         </script>
21     </body>
22 </html>

 

 

 

2、new Event('resize') + dispatchEvent

<script>
    window.onresize = function() {
        alert('触发成功');
    };
    $(function () {
        //console.log($(window).width());
        //console.log($(window).height());
        let myEvent = new Event('resize');
        //console.log(myEvent);
        window.dispatchEvent(myEvent);
    });
</script>

 

 

 
posted @ 2020-03-23 23:43  范仁义  阅读(942)  评论(0编辑  收藏  举报