获得当前窗口的宽度

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhai_15733218875/article/details/81539738
var fullWindowWidth = window.innerWidth
    if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8
      var documentElementRect = document.documentElement.getBoundingClientRect() // 返回一个矩形对象,包含四个属性:xy、 width、 height、 left、 top、 right和bottom
      fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left)
    }

以上就是了,
扩展:
1. window.innerWidth 和 window.width 区别
前者是js方法、后者是jq方法
都是计算窗口宽度,但是前者包含滚动条的宽度,后者不包含
2.document.body.clientWidth 网页可见区域宽
想要判断窗口是否有滚动条

 Modal.prototype.checkScrollbar = function () {
    var fullWindowWidth = window.innerWidth (包含滚动条的窗口宽度)
    if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8
      var documentElementRect = document.documentElement.getBoundingClientRect()
      fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left)
    }
    this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth //即是否有滚动条
  }

3、 offsetWidth 实际获取的是盒模型 (width+border + padding)
4、这里写图片描述

猜你喜欢

转载自blog.csdn.net/zhai_15733218875/article/details/81539738
今日推荐