window.onresize监听事件

window.onresize监听事件

  onresize 事件会在窗口或框架被调整大小时发生。

  支持onresize的标签:<a>, <address>, <b>, <big>, <blockquote>, <body>, <button>, <cite>, <code>, <dd>, <dfn>, <div>, <dl>, <dt>, <em>, <fieldset>, <form>, <frame>, <h1> to <h6>, <hr>, <i>, <img>, <input>, <kbd>, <label>, <legend>, <li>, <object>, <ol>, <p>, <pre>, <samp>, <select>, <small>, <span>, <strong>, <sub>, <sup>, <table>, <textarea>, <tt>, <ul>, <var>

一、屏幕的改变:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, width=device-width">
    <meta content="telephone=no" name="format-detection">
</head>
<body>
<label id="show"></label>
<script>
    window.onresize = adjuest;
    adjuest();
    function adjuest(){
       var label = document.getElementById("show");
       label.innerHTML = "width = "+window.innerWidth+";height="+window.innerHeight;
    }
</script>
</body>
</html>

注:宽高会随着屏幕大小而改变

二、div大小的改变:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<div id="show_div" style="background-color: lightblue; 100%;height: 300px;"></div>
<label id="show"></label>
<script>
    window.onresize = adjuest;
    adjuest();
    function adjuest(){
        var label = document.getElementById("show");
        var divCon = document.getElementById("show_div");
        label.innerHTML = "width = "+divCon.offsetWidth+";height="+divCon.offsetHeight;
    }
</script>
</body>
</html>

注:宽会随着div的宽度大小而改变

三、发现浏览器窗口缩小时会触发两次 onresize 事件,解决方法:

当浏览器窗口大小改变的时候将会触发onresize事件。

可以监控该事件的发生做一些响应式的处理:

JS:

window.onresize(function(){
    //code
}):

jQuery:

$(window).resize(function(){
    //code
});

在监控的过程中发现每次改变浏览器窗口的时候 onresize 事件都会触发两次(产生 的原因貌似比较复杂,网上没有定论,发现在最大化浏览器的时候,浏览器也会闪一下,有两次窗口大小的改变)。

解决方法: setTimeout()

function windowResizeEvent(callback) {
    var firstFire = null;

    window.onresize = function () {
        if(firstFire === null) {
            firstFire = setTimeout(function() {
                firstFire = null;
                callback();
            }, 100);
        }
    }
}
原文地址:https://www.cnblogs.com/Michelle20180227/p/9907414.html