• 认真地记录技术中遇到的坑!
  • 能摸鱼真是太好啦!嘿嘿嘿!

HTML页面中JavaScript能获取到的各种屏幕大小信息

JavaScript 悠悠 6年前 (2017-12-27) 3916次浏览 0个评论

在HTML页面中,通过JavaScript代码访问 window 对象,能够获取到很多表征屏幕大小的信息,下面列举并加以区分。

window 对象中的屏幕信息

window.innerheight、 window.innerwidth

  • 只读属性,以像素计
  • 浏览器窗口的文档显示区的高度和宽度
  • 不包括菜单栏、工具栏以及滚动条等的高度
  • IE8以下不支持这些属性,用 document.documentElement 或 document.body (与 IE 的版本相关)的 clientWidth 和 clientHeight 属性作为替代

window.outerheight、 window.outerwidth

  • 只读属性,以像素计
  • 整个浏览器窗口的高度和宽度
  • 常用于设置 window.open 打开的窗口宽度和高度
  • IE8以下不支持此属性,且没有提供替代的属性

window.screenLeft、 window.screenTop、 swindow.creenX、 window.screenY

  • 只读属性,整数
  • 浏览器窗口的左上角在屏幕上的的 x 坐标和 y 坐标
  • IE、Safari 和 Opera 支持 screenLeft 和 screenTop
  • Firefox 和 Safari 支持 screenX 和 screenY

window.screen.availHeight、 window.screen.availHeightavailWidth

  • 以像素计
  • 浏览器的屏幕的可用高度和宽度
  • Windows中不包括分配给半永久特性(如屏幕底部的任务栏)的垂直空间

window.screen.height、 window.screen.width

  • 以像素计
  • 显示器屏幕的高度和宽度
  • 调整显示设备的分辨率会发生变化
  • 少部分移动设备上面的值并不是真正的显示屏大小,如三星S8

document 对象中的屏幕信息

很复杂!真的很复杂!这些值根据是否指定 DOCTYPEIE 、网页是否超过窗口宽度 有关系。而且FireFox,Chrome这些主流浏览器里面针对元素的 clientWidth、 offsetWidth、 scrollWidth信息技术都有各自的标准。下面简单说明作为参考。详细新在实际应用中进行调整。

下面的 document.body 和 document.documentElement 类似,body也是一个DOM element。

document.body.clientHeight、 document.body.clientWidth

  • 浏览器中可显示内容区域的高度和宽度
  • document.documentElement 表示元素的可见高度和宽度
  • 与页面内容多少无关
  • 滚动条不算在内,padding算在内
  • clientHeight = topPadding + bottomPadding+ height – scrollbar.height

document.body.offsetHeight、 document.body.offsetWidth

  • 包括边线的网页内容可见区域高度和宽度
  • offsetHeight = clientHeight + 滚动条 + 边框

document.body.scrollHeight、 document.body.scrollWidth

  • 网页正文全文高度和宽度
  • 不同的浏览器中 scrollHeight 和 clientHeight 的大小关系不一样

解决方案

可以使用下面的方式折中取 scrollWidth 和 clientWidth :

var scrollWidth = Math.max(document.documentElement.scrollWidth, document.body.scrollWidth);
var clientWidth = document.documentElement.clientWidth || document.body.clientWidth;

下面列举通用HTML元素 element 的大小属性信息:

  • element.clientHeight : 元素的可见高度
  • element.clientWidth : 元素的可见宽度
  • element.offsetHeight : 元素的高度
  • element.offsetWidth : 元素的宽度
  • element.offsetLeft : 元素的水平偏移位置
  • element.offsetTop : 元素的垂直偏移位置
  • element.offsetParent : 元素的偏移容器
  • element.scrollHeight : 元素的整体高度
  • element.scrollLeft : 元素左边缘与视图之间的距离
  • element.scrollTop : 元素上边缘与视图之间的距离
  • element.scrollWidth : 元素的整体宽度

喜欢 (1)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址