浏览器大小(宽度和高度)

don*_*ono 48 javascript browser jquery

我正在尝试检测浏览器的当前大小(宽度和高度).我知道它在jQuery中非常容易$(document).width and $(document).height,但是我不想将jQuery lib的大小添加到项目中,所以我宁愿使用内置的JavaScript.使用JavaScript做同样事情的简短而有效的方法是什么?

Joe*_*oel 84

// first get the size from the window
// if that didn't work, get it from the body
var size = {
  width: window.innerWidth || document.body.clientWidth,
  height: window.innerHeight || document.body.clientHeight
}
Run Code Online (Sandbox Code Playgroud)

  • 这可以使用短路操作器进行优化.例如:`width:window.innerWidth || document.body.clientWidth` (4认同)

ken*_*bec 8

function getWindowSize(){
 var d= document, root= d.documentElement, body= d.body;
 var wid= window.innerWidth || root.clientWidth || body.clientWidth, 
 hi= window.innerHeight || root.clientHeight || body.clientHeight ;
 return [wid,hi]
}
Run Code Online (Sandbox Code Playgroud)

IE浏览器是唯一不使用innerHeight和Width的浏览器.

但是没有"标准" - 只是浏览器实现.

在检查body之前测试html(document.documentElement)clientHeight-如果它不是0,它是'viewport'的高度,body.clientHeight是body的高度 - 可以大于或小于window .

向后模式为根元素返回0,并从主体返回窗口(视口)高度.

与宽度相同.