屏幕宽高的一些获取方法汇总

document.documentElement.clientWidth;
document.documentElement.clientHeight;
这个得到的是设备像素可见宽高,比如iPhone 4s在微信内设置了viewport为1的时候为320*416(手机480 - 微信状态栏64)

比如上面说的screen.width screen.height这些数据在有的手机上并不准确,比如三星的某些型号。

viewport和屏幕的真实尺寸并不是对应的,如在Safari Mobile中viewport默认宽度(320px)是屏幕真实尺寸(640px)的一半,
这里不管是用window.innerHeight还是window.screen.width拿到的都是320px。
 

screen对象

screen对象包含了显示设备的信息。

  • screen.height:显示设备的高度,单位为像素。
  • screen.width:显示设备的宽度,单位为像素。

以上两个属性,除非调整显示设备的分辨率,否则看作是常量,不会发生变化。

下面是根据屏幕分辨率,将用户导向不同网页的代码。

if ((screen.width<=800) && (screen.height<=600)) {
    window.location.replace('small.html');
} else {
    window.location.replace('wide.html');
}

window.innerHeightwindow.innerWidth属性,返回网页在当前窗口中可见部分的高度和宽度,即“视口”(viewport),单位为像素。

当用户放大网页的时候(比如将网页从100%的大小放大为200%),这两个属性会变小。因为这时网页的像素。

window.outerHeightwindow.outerWidth属性返回浏览器窗口的高度和宽度,包括浏览器菜单和边框,单位为像素。


function getViewportSize () { 
    return { 
     window.innerWidth || document.documentElement.clientWidth ||     document.body.clientWidth, 
    height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight 
    };
 }    

  

手机浏览器窗口的可视高度会由顶部地址栏的隐藏与否而变化,可以监听window的resize事件准确获取窗口高度:
var winHeight = window.innerHeight;

window.addEventListener('resize', function(event){
    winHeight = window.innerHeight;
});

  





原文地址:https://www.cnblogs.com/wu-hou/p/6905254.html