preface

In the actual development, we often encounter offsetXXX, scrollXXX and clientXXX properties, but the differences between these properties are not very big, leading to confusion when using them. Next, I will use the most intuitive way to let you once and for all.

The relevant attributes are listed first:

  • offsetWidth/offsetHeight/offsetTop
  • clientWidth/clientHeight
  • scrollWidth/scrollHeight/scrollTop

offsetXXX

First look at the attributes associated with offset:

  • offsetWidth/offsetHeightCSS for an element.”High standard width“, which contains the border, inner margin, element content, and scroll bar (if any).

Using the image on MDN, you can see the offsetWidth of the element, which is the “actual space” taken up by the element on the page. At the same time, when the shape of the element changes (such as enlarging or shrinking), offsetWidth represents the layout width and height of the element, not the actual rendered width and height. To get the width and height of the render, use the getBoundingClientRect() method to calculate the true offsetWidth

clientXXX

  • clientWidth/clientHeightRepresents the value of an element.High content of wide“, contains the element content and the inner margin

That is, if you only want to get the size of the display content area, use clientWidth

scrollXXX

  • scrollWidth/scrollHeightRepresents the actual size of an element’s content area, including scrollable portions (content and inner margins) that are not in the page

It can be understood as an enhanced version of clientXXX and is the size of the entire content

xxxTop

  • offsetTopIs the distance between the top of the current element and the top of the nearest parent element, regardless of the scrollbar
  • scrollTopIn the case of scroll bars, the distance from the element’s visible area to the top pixel of the element, that is, how far it has been scrolled

Distinction and Connection

To summarize the differences and connections:

  • offsetXXXCan be seen asclientXXX+ outer border + scroll bar (if available)
  • scrollXXXCan be seen asclientXXX+ Hidden area size (if there is scrolling)

digression

ElementUI has been reading the source code for a while. The next article is the Select component, which I have been reading for several days. Finally, IT is almost finished. Stay tuned if you want to know more.