document.documentElement
|| document.body
为了消除标准模式和怪异模式之间的差别而做的兼容。
当我们在获取滚动位置时,常常使用document.documentElement.scrollTop
来获取垂直滚动的偏移值,document.documentElement.scrollLeft
来获取水平滚动的偏移值。
但是为什么会常常见到document.documentElement.scrollTop || document.body.scrollTop
这种兼容写法,到底是在兼容什么?
首先需要知道DTD的概念,DTD
全称Document Type Definition
,其实就是在文档开头用<!DOCTYPE html>
去声明文档为标准模式(CSS1Compat)。现在浏览器可以通过document.compatMode
获取该字段。与标准模式相对应的就是怪异模式(backCompat)。如果document.compatMode
为undefined时也为怪异模式。
在标准模式下,现代浏览器(包括IE9及以上)都能通过document.documentElement['scrollTop' | 'scrollLeft']
去获取滚动偏移量,但是在怪异模式下是无法使用的,需要替换成document.body['scrollTop' | 'scrollLeft']
。除了scrollTop
、scrollLeft
,clientWidth
、clientHeight
也需要同样的兼容。