JavaScript窗口

来源:互联网 发布:christopher bu知乎 编辑:程序博客网 时间:2024/06/16 12:15

JavaScript窗口属性

JS中窗口是window对象的属性之一,我们常用于测试浏览器以及浏览器页面的分辨率,即宽高,但是在不同的浏览器有不同的测试方式,这就会导致兼容性问题,本文终点介绍各属性在不同浏览器的实现方式以及兼容性处理方法。

window中的窗口位置

各主流浏览器都提供了screenLeft和screenTop两个属性,分别同于测试浏览器窗口左上角的坐标位置(相对于显示器左上角)。但是Firefox在sreenX和screenY属性中也提供了相同的位置信息属性,所以兼容性写法如下所示:

var left = (typeof window.screenLeft == "number") ? window.screenLeft : window.screenX;var top = (typeof window.screenTop == "number") ? window.screenTop : window.screenY;    

typeof泳衣确定screenLeft和screenTop属性是否在浏览器中存在,如果不存在,则使用screenX和screenY方法,以此获得浏览器窗口的坐标位置。
但是在IE和Opera浏览器中,screenLeft和screenTop两个属性的值与其他的浏览器有所不同,screenLeft和screenTop中的坐标始终多出一些像素,即使浏览器最大化适应整个屏幕,这两个属性的不为0,其他的浏览器都为0。

window中的窗口大小

所有主流浏览器提供了四个属性:innerWidth、innerHeight、outerWidth和outerHeight(IE8及其之前的版本不支持),但是这四个属性在不同的浏览器返回的是不同的值
IE9+、Safari和Firefox中outerWidth和outerHeight返回浏览器本身的窗口大小;
Opera中outerWidth和outerHeight返回页面视图容器的大小; innweWidth和innerHeight返回该容器中页面视图区域的大小(减去边框宽度);
Chrome中innerWidth、innerHeight、outerWidth和outerHeight返回的值都相等,即页面可视区域的大小。
在IE8及之前的浏览器中虽然没有上述的四个属性,但是却有类似的四个属性:
标准模式:document.documentElement.clientWidth和document.documentElement.clientHeight表示页面可视区域的大小;
混杂模式:document.body.clientWidth和document.body.clientHeight表示相同的信息。
混杂模式在Chrome浏览器中也有上述的四个属性,也都表示箱相同的值。
所以检测浏览器窗口以及可视区域窗口的大小有以下兼容性写法:

var pageWidth = window.innerWidth;var pageHeight = window.innerHeight;    if(typeof pageWidth !== "number"){        if(document.compatMode == "CSS1Compat"){            pageWidth = document.documentElement.clientWidth;        } else {            pageWidth = document.body.clientWidth;            pageHeight = document.body.clientHeight;    }} 

在移动设备中,window.innerWidth和window.innerHeight表示可见区域的大小,但是移动IE浏览器不支持这两个属性,只能通过document.documentElement.clientWidth和document.documentElement.clientHeight两个属性获得可视区域的大小。

window中的窗口弹出

使用window.open()方法可以导航到一个特定的URL,以及打开的方式,它通常有四个参数:需要打开的URL地址,窗口打开的方式,窗口的信息(位置,大小等)以及记录此窗口的Boolean值。但是有些浏览器不支持窗口弹出,因为在网页上可能会有不安全的窗口弹出,所以大多数浏览器都内置有弹出窗口屏蔽程序。检测方法如下

var blocked = false;try{     var baidu = window.open("http://www,baidu.com", "_blank");     if(baidu == null){         blocked = true;    }} catch (ex){     blocked = true;      } if(blocked){     alert("The popup was blocked!"); }
原创粉丝点击