Javascript获取element内容高度的方法
jQuery
jQuery有三个获取高度的方法:.height()、.innerHeight()和.outerHeight()。.height()
返回当前元素的经过样式计算过的高度值,也可以用来设置元素的高度值。这个高度值是元素内容的高度值,不包含padding,margin和border。
.innerHeight()
为元素的当前计算高度值,包含元素内容的高度值和padding,不包括margin和border。
.outerHeight()
元素的当前计算高度值,包含元素内容的高度值、padding,border和选择性的margin。
Javascript
一般来说在Javascript有三种高度:clientHeight,offsetHeight和scrollHeight。clientHeight
返回元素的inner height,包含内容高度和padding,不包含水平滚动条高度,border和margin。offsetHeight
offsetHeight包含元素的内容高度、border、padding和水平滚动条的高度(如果有则加上)。scrollHeight
scrollHeight包含了不可见部分元素内容整体的高度和padding。也可以描述为,clientHeight + 不可见部分内容高度。 总结jQuery和Javascript获取元素高度的知识后,再来看看我的问题。在Javascript中寻找替代jQuery的.height()的方法。从列出的方法来看,clientHeight、offsetHeight和scrollHeight均无法代替jQuery的height()。从height()的底层实现来看,用到getComputedStyle方法,所以这个应该是正解了。var element_height = window.getComputedStyle(element, null).height
使用如上方法,可以得到带px单位的元素高度。如果不想带px,则:
var element_height = window.getComputedStyle(element, null).height.split("px")[0]
所以在原生Javascript中,上面的方法则可以代替jQuery的.height()。