【问题标题】:Finding height() of window in Vanilla JavaScript在 Vanilla JavaScript 中查找窗口的高度()
【发布时间】:2020-05-29 14:16:45
【问题描述】:

我正在尝试用纯原生 JS 编写程序。我必须找到窗口的高度和宽度。在 JQuery 中,我使用.height()。在线搜索显示 clientHeight 或 innerHeight 应该等同于 height() 但是在我的程序中 $(widow).height() 和 window.innerHeight 控制台记录两者的不同值(4500 用于 height() 和 @987654330 @ for innerHeight..and undefined for window.clientHeight)

如何找到与$(widow).height() 等效的Vanilla JS?

【问题讨论】:

  • 这能回答你的问题吗? Get the window height
  • 谢谢。尽管正如我在帖子中所说,innerHeight 返回的值与height() 不同,但document.documentElement.offsetHeight 似乎有效。虽然答案说这是针对旧浏览器的,所以我想知道为什么这些值不同,以及它是否真的是最好的解决方案。

标签: javascript css height


【解决方案1】:

console.log('Window height',window.screen.height);
console.log('Inner height',window.innerHeight);

【讨论】:

    【解决方案2】:

    滚动的全高

    const height = Math.max(
      document.body.scrollHeight, document.documentElement.scrollHeight,
      document.body.offsetHeight, document.documentElement.offsetHeight,
      document.body.clientHeight, document.documentElement.clientHeight
    );
    

    【讨论】:

    • document.body 高度不一定与窗口高度相同。
    • 在不同的浏览器中,这个值可能不同。
    • 或者我们可以只使用 document.body.scrollHeight | document.documentElement.scrollHeight... 这将返回一个滚动高度..
    • document.documentElement.offsetHeight 似乎有效。您能否详细说明为什么会这样,和/或为什么我需要尝试三种方法并选择最高的一种?
    • 您应该使用最大值,因为某些浏览器可以有不同的值。示例:在 opera 版本 x.x.x 中,我们有 clientHeight > scrollHeight 等。但在最新版本的 opera 中一切都好...这段代码可以让您避免来自不同浏览器的所有版本的意外行为..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    • 2014-05-20
    • 2016-07-08
    • 1970-01-01
    相关资源
    最近更新 更多