$(document).width() versus document.body.clientWidth



这两个声明之间有什么区别吗?我想用其中一个来修复移动版响应网站上的一些css问题。一些教程建议使用$(document).width(),而其他教程则建议使用document.body.clientWidth。我知道第一个是jquery,第二个是纯JavaScript,但除此之外还有什么区别吗?哪一个更好用?

我想这样使用它们:

if ($(document).width() < 768) { ... }

if (document.body.clientWidth < 768) { ... }

是的,它们不同。jQuery做了很多事情来尝试规范化结果。

参见源代码:

if (elem.nodeType === 9) {
    doc = elem.documentElement;
    // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
    // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
    return Math.max(
    elem.body["scroll" + name], doc["scroll" + name], elem.body["offset" + name], doc["offset" + name], doc["client" + name]);
}

document.body.clientWidth=$(document).width()+(左填充+右填充)

最新更新