• Width & Height

    Width 与 Height 获取方法相同,下面以 Height 为例:

    • Window height

      1. // window height
      2. // 含 scrollbar
      3. window.document.documentElement.clientHeight;
      4. // 不含 scrollbar,与 jQuery 行为一致
      5. window.innerHeight;
    • Document height

      1. // jQuery
      2. $(document).height();
      3. // Native
      4. const body = document.body;
      5. const html = document.documentElement;
      6. const height = Math.max(
      7. body.offsetHeight,
      8. body.scrollHeight,
      9. html.clientHeight,
      10. html.offsetHeight,
      11. html.scrollHeight
      12. );
    • Position

      获得匹配元素相对父元素的偏移

      1. // jQuery
      2. // Native
      3. { left: el.offsetLeft, top: el.offsetTop }
    • Offset

      获得匹配元素相对文档的偏移

      1. // jQuery
      2. $el.offset();
      3. // Native
      4. function getOffset (el) {
      5. const box = el.getBoundingClientRect();
      6. return {
      7. top: box.top + window.pageYOffset - document.documentElement.clientTop,
      8. left: box.left + window.pageXOffset - document.documentElement.clientLeft
      9. }
      10. }
  • Scroll Top

获取元素滚动条垂直位置。

  1. // jQuery
  2. $(window).scrollTop();
  3. // Native