【问题标题】:$(document).width() versus document.body.clientWidth$(document).width() 与 document.body.clientWidth
【发布时间】:2013-12-02 21:35:02
【问题描述】:

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

我想这样使用它们:

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

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

【问题讨论】:

  • 它们应该返回完全相同的值,所以你使用哪一个取决于你。
  • 主要区别在于第一个是借助 jQuery 编写的,而第二个是用纯 JavaScript 编写的。

标签: javascript jquery


【解决方案1】:

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

the source code:

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]);
}

【讨论】:

    【解决方案2】:

    document.body.clientWidth = $(document).width() + (left padding + right padding)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-14
      • 1970-01-01
      • 2014-12-26
      • 2011-06-14
      • 1970-01-01
      • 2012-10-28
      • 2014-04-29
      • 2017-01-01
      相关资源
      最近更新 更多