美文网首页
09-获取网页宽高

09-获取网页宽高

作者: 仰望_IT | 来源:发表于2019-05-14 08:57 被阅读0次
  • innerWidth / innerHeight
    • 注意点: innerWidth / innerHeight 只能在IE9以及IE9以上的浏览器中才能获取
      console.log(window.innerWidth);  // 1920
      console.log(window.innerHeight);  // 903
    
  • document.documentElement.clientWidth / document.documentElement.clientHeight
    • 注意点: 可以用于在IE9以下的浏览器的标准模式中获取
    • 浏览器在渲染网页的时候有两种模式"标准模式"/"混杂模式(怪异模式)"
    • 默认情况下都是以标准模式来进行渲染的(CSS1Compat)
      console.log(document.documentElement.clientWidth);  // 1920
      console.log(document.documentElement.clientHeight);  // 903
    
  • 混杂模式
    • 如果网页没有书写文档声明, 那么就会按照"混杂模式(怪异模式)"来进行渲染(BackCompat)
    • 注意点: 在混杂模式中利用如下的方式获取可视区域的宽高
      console.log(document.compatMode);   // 通过这行代码可以知道现在是在什么模式下, 默认是CSS1Compat
    
      console.log(document.body.clientWidth);  // 1920
      console.log(document.body.clientHeight);  // 903
    
  • 兼容性处理
      let {width, height} = getScreen();
      console.log(width);
      console.log(height);
    
      function getScreen() {
          let width, height;
          if (window.innerWidth){ // IE9及IE9以上
              width = window.innerWidth;
              height = window.innerHeight;
          } else if (document.compatMode === "BackCompat"){   // IE9以下混杂模式
              width = document.body.clientWidth;
              height = document.body.clientHeight;
          } else {    // IE9以下标准模式
              width = document.documentElement.clientWidth;
              height = document.documentElement.clientHeight;
          }
          return {
              width: width,
              height: height
          }
      }
    

相关文章

网友评论

      本文标题:09-获取网页宽高

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