窗口的 width/height

  1. 为了获取窗口(window)的宽度和高度,我们可以使用 document.documentElement 的 clientWidth/clientHeight,返回的是可用于内容的文档的可见部分的 width/height,不包含滚动条。
  2. window.innerWidth/innerHeight 包括了滚动条。

文档的 width/height

  1. 为了可靠地获得完整的文档高度,我们应该采用以下这些属性的最大值:
  2.         
                let scrollHeight = Math.max(
                    document.body.scrollHeight, document.documentElement.scrollHeight,
                    document.body.offsetHeight, document.documentElement.offsetHeight,
                    document.body.clientHeight, document.documentElement.clientHeight
                );
            
        

获得当前滚动

  1. DOM 元素的当前滚动状态在其 scrollLeft/scrollTop 属性中。
  2. 对于文档滚动,在大多数浏览器中,我们可以使用 document.documentElement.scrollLeft/scrollTop,但在较旧的基于 WebKit 的浏览器中则不行,例如在 Safari(bug 5991)中,我们应该使用 document.body 而不是 document.documentElement。
  3. 幸运的是,我们根本不必记住这些特性,因为我们可以从 window.pageXOffset/pageYOffset 中获取页面当前滚动信息,这些属性是只读的。
  4. 我们也可以从 window 的 scrollX 和 scrollY 属性中获取滚动信息。由于历史原因,存在了这两种属性,但它们是一样的:window.pageXOffset 是 window.scrollX 的别名。window.pageYOffset 是 window.scrollY 的别名。

滚动:scrollTo,scrollBy,scrollIntoView

  1. 可以通过更改 scrollTop/scrollLeft 来滚动常规元素。
  2. 可以使用 document.documentElement.scrollTop/scrollLeft 对页面进行相同的操作(Safari 除外,而应该使用 document.body.scrollTop/Left 代替)。
  3. 或者,有一个更简单的通用解决方案:使用特殊方法 window.scrollBy(x,y) 和 window.scrollTo(pageX,pageY)。
  4. scrollIntoView

禁止滚动

  1. document.body.style.overflow = "hidden"
  2. document.body.style.overflow = ""