js窗口属性

作者: 葶寳寳 | 来源:发表于2017-08-13 13:40 被阅读0次

    screenLeft、screenTop属性

    1. screenLeftscreenTop分别用于表示窗口相对于屏幕左边和上边的位置。
     console.log("window.screenLeft = " + window.screenLeft); //51
     console.log("window.screenTop = " + window.screenTop); //24
    
    263589321.jpg
    1. 有些浏览器可能不支持上边的两个属性,但支持screenXscreenY属性。

      所以,跨浏览器取得窗口左边和上边的位置用如下代码:

       var leftPos = (typeof window.screenLeft == "number") ?     window.screenLeft : window.screenX;
      
       var topPos = (typeof window.screenTop == "number") ?    window.screenTop : window.screenY;
      
    2. 如果将视图区(如下图)最大化,此时的screenLeftscreenTop均为0.

    最大化视图区.png

    innerWidth、innerHeight、outerWidth、outerHeight属性

    1. outerWidth、outerHeight:返回浏览器窗口本身的尺寸(包括窗口标题、工具栏、状态栏等)。
      innerWidth、innerHeight:表示容器中页面视图区的大小(包括滚动条)。
    来自网络图片.png
    1. 对于Chrome来说,outerWidthouterHeightinnerWidthinnerHeight返回相同的值,即视口的大小。

    2. 在不支持window.innerHeight的浏览器中,可以通过以下方法读取页面视口的大小, 它们的大小和window.innerHeight是一样的(其实不太一样):
      document.documentElement.clientWidth
      document.body.clientWidth

      所以,跨浏览器获取页面视口大小代码如下:

      var pageWidth = window.innerWidth;
      var 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;
          }
      }
      
    3. 三者大小关系:

    • window.innerHeight包括整个DOM:内容、边框以及滚动条。

    • documentElement.clientHeight不包括整个文档的滚动条,但包括<html>元素的边框。

    • body.clientHeight不包括整个文档的滚动条,也不包括<html>元素的边框,也不包括<body>的边框和滚动条。

    参考文档:
    视口的宽高与滚动高度

    相关文章

      网友评论

        本文标题:js窗口属性

        本文链接:https://www.haomeiwen.com/subject/ougsrxtx.html