• 获取window窗口大小


    窗口大小

      跨浏览器确定一个窗口的大小不是一件简单的事。IE9+、Firefox、Safari、Opera和Chrome均为此提供了4个属性:innerWidth、innerHeight、outerWidth和outerHeight。在IE9+、Safari和Firefox中,outerWidth和outerHeight返回浏览器窗口本身的尺寸(无论是从最外层的window对象还是从某个框架访问)。在Opera中,这两个属性的值表示页面视图容器的大小。而innerWidth和innerHeight则表示该容器中页面视图区的大小(减去边框宽度)。在Chrome中,outerWidth、outerHeight 与innerWidth、innerHeight返回相同的值,即视口(viewport)大小而非浏览器窗口大小。IE8及更早版本没有提供取得当前浏览器窗口尺寸的属性;不过,它通过DOM提供了页面可见区域的相关信息。

      在IE、Firefox、Safari、Opera和Chrome中,document.documentElement.clientWidth和document.documentElement.clientHeight中保存了页面视口的信息。在IE6中,这些属性必须在标准模式下才有效;如果是混杂模式,就必须通过document.body.clientWidth和document.body.clientHeight取得相同信息。而对于混杂模式下的Chrome,则无论通过document.documentEle-ment还是document.body中的clientWidth和clientHeight属性,都可以取得视口的大小。 

    虽然最终无法确定浏览器窗口本身的大小,但却可以取得页面视口的大小,如下所示。

    var pageWidth = window.innerWidth, 
        pageHeight = window.innerHeight; 
    
    if (typeof pageWidth != "number"){ 
        //标准模式
        if (document.compatMode == "CSS1Compat"){ 
            pageWidth = document.documentElement.clientWidth; 
            pageHeight = document.documentElement.clientHeight; 
        //怪异模式
        } else { 
            pageWidth = document.body.clientWidth; 
            pageHeight = document.body.clientHeight; 
        } 
    } 

      PS: 对于移动设备,window.innerWidth和window.innerHeight保存着可见视口,也就是屏幕上可见页面区域的大小。移动IE 浏览器不支持这些属性,但通过document.documentElement.client-Width和document.documentElement.clientHeihgt提供了相同的信息。随着页面的缩放,这些值也会相应变化。

  • 相关阅读:
    [LeetCode] 1190. Reverse Substrings Between Each Pair of Parentheses
    [LeetCode] 923. 3Sum With Multiplicity
    [LeetCode] 643. Maximum Average Subarray I
    [LeetCode] 669. Trim a Binary Search Tree
    [LeetCode] 1743. Restore the Array From Adjacent Pairs
    [LeetCode] 888. Fair Candy Swap
    [LeetCode] 1102. Path With Maximum Minimum Value
    [LeetCode] 1631. Path With Minimum Effort
    [LeetCode] 1522. Diameter of N-Ary Tree
    [LeetCode] 1376. Time Needed to Inform All Employees
  • 原文地址:https://www.cnblogs.com/fengzekun/p/3909557.html
Copyright © 2020-2023  润新知