Window size, scroll


<!DOCTYPE HTML> effect

There is this line is the standard mode
, and the promiscuous mode is forward compatible with the old rendering method.

View the scroll distance of the scroll bar

  • window.pageXOffset / pageYOffset IE8 and below are not compatible
  • document.body/documentElement.scrollLeft/scrollTop
    Compatibility is confused, two values ​​are opposite, one is 0, and the two values ​​are added when used

View viewport size

  • window.innerWidth/innerHeight
    IE8 and below are not compatible
  • document.documentElement.clientWidth/clientHeight
    In standard mode, any browser is compatible
  • document.body.clientWidth/clientHeight
    Weird mode

The difference between innerWidth and clientWidth

If there exists a scroll bar, and scroll bar takes up some space, it clientWidth/clientHeightwill provide no scroll bars (subtracting it) is width/height. In other words, they return the visible part of the document that can be used for content width/height.

And window.innerWidth/innerHeight includes scroll bars.

    alert( window.innerWidth ); // 整个窗口的宽度
    alert( document.documentElement.clientWidth ); // 减去滚动条宽度后的窗口宽度

View the geometric dimensions of elements

  • domEle.getBoundingClientRect();
    The returned result is not real-time.
    Understand that there are other element sizes behind

  • dom.offsetWidth dom.offsetHeight
    Return width and height

  • dom.offsetLeft dom.offsetTop
    For elements without a positioned ancestor, return the coordinates relative to the document; for elements with a positioned ancestor, return the coordinates relative to the nearest positioned parent.
    Regardless of the displacement generated by margin or position, it will be displayed

- dom.offsetParentReturn to nearest positioned ancestor
body.offsetParentreturnnull

Scroll bar

  • scroll(x,y) / scrollTo(x,y)
    The two methods are the same, jump to the position of xy

  • scrollBy(x,y);
    Cumulative scroll

No scrolling

For non-scrollable document, only you need to set document.body.style.overflow = "hidden"the page will be frozen at its current rolling on.
The disadvantage of this method is that the scroll bar disappears. If the scroll bar takes up some space, the space it originally occupies will be vacated, and the content will "jump" in to fill it.

You can add padding on the right side of the body to offset the scroll bar changes

Realize the demo:

  1. Expand more -> When collapsed, scroll jumps to the position where you clicked to expand
  2. scrollBy() realizes automatic reading

Guess you like

Origin blog.csdn.net/S_aitama/article/details/107475382