我爱编程

JS中元素高度相关方法

2018-06-27  本文已影响0人  夜舞暗澜_3ea2

按照获取范围整理:

1. content

$(node).height()

image

2. content+padding

$(node).innerHeight()

image

原生JS:

  1. node.clientHeight只读属性,元素content+padding目前可视的部分,不包括滚动条。
  2. node.scrollHeight只读属性,元素content+padding所有可滚动部分,不包括滚动条
  3. window.innerHeight可以返回窗口可视区高度。
* clientHeight和scrollHeight的区别

3. content+padding+border

$(node).outerHeight()

image

原生JS

  1. node.offsetHeight,只读属性,content+padding+元素水平滚动条。这个属性值会被四舍五入为整数值。
  2. window.outerHeight可以返回整个窗口的高度,包括地址栏菜单栏状态栏等等一系列乱七八糟的东西(有什么使用场景希望大家给个补充~)。
    注:window不是一般的DOM元素,比如它就没有clientHeight属性。

4. content+padding+border+margin

$(node).outerHeight(true)
(示意图同上)


特殊的:window、document

window和document都不是DOM元素,不能按普通的DOM元素调用API。

window:窗口

window本身只有两个高度:

但是window还有一个元素,它也有两个height:

window.screen:用户屏幕信息

document:文档

document是指整个html文件。它并不是一个页面更不是一个DOM元素,所以document没有高度。
那么document到底是个什么位置呢?下面给出主要元素的相对关系:

document.documentElement => html
document.documentElement.childeNodes[1] => body
document.body => body

document.documentElement

上面说了document.documentElement就是html标签,DOM元素会有的属性,document.documentElement就会有,包括clientHeight,scrollHeight,offsetHeight。
一般的,window.innerHeight === document.documentElement.clientHeight

参考资料:
MDN中文文档:https://developer.mozilla.org/zh-CN/
jQuery文档:https://api.jquery.com/

上一篇 下一篇

猜你喜欢

热点阅读