在开发中发现了JQuery和Zepto两个关于获取document的坑。html
复现问题:bash
$(document).scrollTop();
// 发现获得的值是 undefined
$(document.body).scrollTop();
// 这个是有值得复制代码
这时候咱们思考一下为何?查看源码spa
# zepto
document = window.document
# JQ 一样的代码
document = window.document
可是jq对window.document.documentElement作了处理var documentElement = document.documentElement;复制代码
咱们经过打印,查看原生的code
console.dir(document);
console.dir(document.constructor); => ƒ HTMLDocument() { [native code] }
console.dir(document.documentElement);
console.dir(document.documentElement.constructor); => ƒ HTMLHtmlElement() { [native code] }复制代码
打印对比咱们会发现。htm
document是没有html的节点属性的。对象
document.documentElement是有html节点属性的。开发
因此咱们经过window.document获取到的对象只是一个文档对象,但document.documentElement才是一个真正的html节点对象。zepto
因此咱们在封装的时候必定要注意,想获取文档的样式属性时候必定要使用document.documentElement 并作兼容处理 document.body文档