window.onresize 事件笔记

onresize的定义方式

一、直接在html中定义

    如<body onresize="doResize()"/>

二、直接给onresize赋值

    可以给window和body的onresize赋值

    如window.onresize=function(){},document.body.onresize=function(){}

三、使用事件监听

    只对window有作用

    如window.addEventListener("resize",fn);

说明:

    1、直接给onresize赋值会覆盖在html中定义。

    2、直接给onresize赋值,window,body只有一个起作用,后定义的会覆盖先定义的

    3、事件监听只对window有效,可以其它方式同时触发。  

 

 

1.浏览器尺寸变化响应事件 :

window.onresize = function(){....}  

 

  获取变更后参数:

 

// 获取到的是变更后的页面宽度  
var currentWidth = document.body.clientWidth;   

  这里需要注意的是,onresize响应事件处理中,因为已经刷新页面,所以获取到的页面尺寸参数是变更后的参数。

 

  如果需要使用到变更之前的参数,需要建一个全局变量保存之前的参数(并且记得在onresize事件中刷新这个全局变量保存新的参数值)。

 

 

2.谷歌浏览器中  window.onresize 事件默认会执行两次(偶尔也会只执行一次,网上大部分说法认为这是Chrome的bug)。 

  解决方法:(为resize设置一个延迟)一般来说推荐新建一个标志位 延时复位控制它不让它自己执行第二次,代码如下:

 

var firstOnResizeFire = true;//谷歌浏览器onresize事件会执行2次,这里加个标志位控制  
  
window.onresize = function()  
{  
 if (firstOnResizeFire) {  
  NfLayout.tabScrollerMenuAdjust(homePageWidth);  
  firstOnResizeFire = false;  
    
  //0.5秒之后将标志位重置(Chrome的window.onresize默认执行两次)  
  setTimeout(function() {  
   firstOnResizeFire = true;  
        }, 500);  
 }  
   
 homePageWidth = document.body.clientWidth; //重新保存一下新宽度  
}  

 

 

例子:

监听屏幕的改变:

<!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>

 

 

效果: 
这里写图片描述

 

2 .监听div大小的改变

 

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<div id="show_div" style="background-color: lightblue;width: 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>

 

效果: 
这里写图片描述

 

.

 

 

 

猜你喜欢

转载自570109268.iteye.com/blog/2406188