Introduction to the

In our daily development, we occasionally encounter the need to get an element style, set an element style, calculate the element position, calculate the scrolling distance, and so on. However, there are so many apis in JS for element position, style, and size that you can get confused if you are not careful. Today, I will take you to find out thoroughly, so that you are no longer confused on this kind of problem.

This article is divided into three parts to get and set the element style, element position size calculation, screen and window position size calculation

  1. The various methods and differences of obtaining element styles, and which method is most appropriate in which case.
  2. Element size and position calculations. Got itclient,scroll,offsetDifferences between the three types of apis.
  3. Screen, window,Object about position, size API, and the differences between each.

Gets and sets the element style

In JS, the most commonly used methods to obtain and set the I element style are mainly ele. Style and getComputedStyle. The methods used to manipulate classes are el.className, el.classList, and getBoundingClientRect.

ele.style

Get the element style by getting its style attribute.

grammar

<head>
  <style>
      .div1 {
        color: red;
      }
  </style>
</head>

<div id="div1" class="div1" style="font-size: 18px">Style tests</div>
Copy the code
const div1 = document.querySelector("#div1");
console.log(div1.style.fontSize); // 18px 
console.log(div1.style.color); // 
Copy the code

The characteristics of

  1. The style attribute values obtained in this way are humped.
  2. This method only gets the inline style of the element.
  3. We can set element styles with this method.

Commonly used method

cssText

We can also use cssText to get the style string.

console.log(div1.style.cssText); // font-size: 18px;
Copy the code

setProperty

We can use the setProperty method to set the element style.

Note that the attributes we set the element style are not written in camel form.

div1.style.setProperty("font-weight".600);
console.log(div1.style.fontWeight); / / 600

// This is also possible
div1.style.fontWeight = 600;
console.log(div1.style.fontWeight); / / 600
Copy the code

getPropertyValue

We can use the getPropertyValue method to get the element style.

Note that we don’t get the element style attribute in camel form.

div1.style.getPropertyValue("font-size"); // 18px

// This is also possible
console.log(div1.style.fontSize)
Copy the code

removeProperty

We can use the removeProperty method to remove an element style.

div1.style.removeProperty("font-weight");

// This is also possible
div1.style.fontWeight = "";
Copy the code

getComputedStyle(ele)

This method is mounted under the Window object, so we can omit the window when we use it.

grammar

console.log(getComputedStyle(div1).fontSize); // 18px
console.log(getComputedStyle(div1).color); // rgb(255, 0, 0)
Copy the code

The characteristics of

  1. The style attribute values obtained in this way are humped.
  2. Can get all rendered styles of elements including inline or inlined styles.
  3. You can only get the style of an element but cannot set the style of an element.

ele.getBoundingClientRect()

This method retrieves the element’s length and width. It also gets the element’s position relative to the browser window (left, right, top, bottom).

grammar

// Bottom: 33 The distance between the box bottom border and the top of the viewport
// height: 25
// left: 8 box left border distance from the left of the viewport
// Right: the distance between the right border of the box and the left of the viewport
// Top: 8 The distance between the box top frame and the top of the viewport
// width: 334 box width
// x: 8 The distance between the upper left corner of the box and the left side of the viewport
Y: 8 The distance between the upper left corner of the box and the top of the viewport

console.log(div1.getBoundingClientRect());
Copy the code

The characteristics of

  1. This method can only get element position and size information, not other style information.
  2. This method does not set element styles.

El. The className, el. ClassList

In addition to the fetch style described earlier, we can also fetch the class name and add a new style to the element by adding the class name.

grammar

console.log(div1.classList.value); // div1
console.log(div1.className); // div1
div1.className += " div2"; // Add a new class name div2
Copy the code

The characteristics of

  1. el.classNameGets the element’s class name string. We can use this method to get the class name or add a new class name
  2. el.classList.valueGets the class name string. If you simply want to get the class name, you can use this method.

conclusion

  1. We use it when we need to style an elementele.styleMethods.
  2. This is used when we need to get all the rendered styles of elementsgetComputedStyle(ele)Methods.
  3. The third method can be used when we need to get the class name or batch set the element style.
  4. We can use this when we need to calculate the position of an element, or whether the element is in the visual window or the size of the elementele.getBoundingClientRect()Methods.

With that in mind, let’s look at some of the elements’ location and size apis

Element position and size calculation

There are client, Scroll and offset apis for element position calculation.

client

Client can be understood simply as visual size.

ClientWidth, clientHeight

ClientWidth is the visible width, which includes the padding but excludes the border, margin, and scrollbar.

ClientHeight is the visible height, which includes the padding but excludes the border, margin, and scrollbar.

ClientTop, clientLeft

ClientTop gets the height of the top border.

ClientLeft gets the width of the left border.

See the example above

  1. clientWidth400px - Scroll bar 15px + left and right inner margins 20 = 405px
  2. clientHeight200px - scroll bar 15px + upper and lower inner margins 20 = 205px
  3. clientTopIs the height of the upper border10px
  4. clientLeftIs the width of the left border10px

scroll

Scroll can be understood simply as the actual size.

ScrollWidth, scrollHeight

ScrollWidth is the same as clientWidth when the element has no scroll bar, and is the visible width. The scrollable width when there is a scrollable bar.

ScrollHeight Is the same height as clientHeight when the element has no scrollbar. The scrollable height when there is a scrollable bar.

ScrollTop, scrollLeft

ScrollTop retrieves how far the element is rolled along the Y-axis.

ScrollLeft captures how close the element is to the X-axis.

Looking at the example above, we used box1.scrollby (20, 10) here; Simulate rolling.

  1. scrollWidth600px + left and right inner margins 20 = 620px
  2. scrollHeight500px + inner margin 20 = 520px
  3. clientTopIs the distance you roll along the y axis10px
  4. clientLeftIs the close distance of rolling on the X-axis20px

offset

Offset can simply be understood as the occupied size (the amount of space occupied in a document).

OffsetWidth, offsetHeight

OffsetWidth width includes padding, border, scrollbar, but not margin

The height offsetHeight includes the padding, border, scrollbar, but not the margin.

offsetParent

OffsetParent is a read-only property that retrieves the element’s most recent ancestor. If not found, return the body element for offsetLeft and offsetTop calculations.

The offsetLeft, offseTop

OffsetLeft Horizontal offset relative to offsetParent

OffseTop Vertical offset relative to offsetParent

See the example above

  1. offsetWidth400px - scroll bar 15px + scroll bar 15px + left and right inner margins 20 + left and right border width 20px = 440px
  2. offsetHeight200px - scroll bar 15px + scroll bar 15px + top and bottom inner margins 20 + top and bottom border width 20px = 240px
  3. offsetParentBecause nothing else is wrapped around it, I return it directlybodyElements.
  4. offsetTopbecausemarginfor20pxSo relative tobodyThe vertical offset distance is20px
  5. offsetLeftbecausemarginfor20pxSo relative tobodyThe horizontal offset distance is20px

Screen and window position and size calculation

screen

Get screen related properties.

Width, height,

Screen. width and screen.height are the width and height of the computer screen, regardless of the size of the browser.

AvailWidth, availHeight

Screen here. AvailWidth, screen. AvailHeight obtained is the actual width and the actual height of a computer screen, if there is need to task bar is removed. It doesn’t matter how big our browser is.

window

Gets browser window related properties.

OuterWidth, outerHeight

OuterWidth returns the full width of the browser, equal to screen.availWidth if the browser is maximized.

OuterHeight returns the total height of the browser, equal to screen.availHeight if the browser is maximized.

InnerWidth, innerHeight

The innerWidth returns the width visible to the browser document, including only the scroll bar.

InnerHeight returns the height of the browser document that is visible, including only the scroll bar, but not the top TAB or bookmark bar.

ScreenX, screenLeft

Window. screenX and window.screenLeft get the distance between the top left corner of the browser window and the left border of the screen.

Windows. ScreenX is not supported by Ie. Firefox is not supported by Window.screenleft

ScreenY, screenTop

Window. screenY and window.screenTop get the distance between the top left corner of the browser window and the border on the screen.

Windows. ScreenY is not supported in Ie. Firefox is not supported in Window. screenTop

ScrollX, scrollY

Window. scrollX returns how far the window is scrolled on the X-axis

Window. scrollY returns how far the window is scrolled along the y axis

PageXOffset, pageYOffset

Window. pageXOffset returns the scrolling distance of the window on the x axis

Window. pageYOffset returns the scrolling distance of the window on the y axis

Note:

ScrollX, scrollY, pageXOffset, and pageYOffset need to be distinguished from scrollTop and scrollLeft. These four apis are only available on window objects.

Compared with scrollX, scrollY, pageXOffset, pageYOffset compatibility is better, generally we only use pageXOffset, pageYOffset on the line. But neither is compatible with IE9 below.

extension

With that in mind, let’s implement a few small requirements that are common in everyday development.

Gets the scroll position of the current page

const getScrollPosition = (el = window) = > ({
  x: el.pageXOffset ! = =undefined ? el.pageXOffset : el.scrollLeft,
  y: el.pageYOffset ! = =undefined ? el.pageYOffset : el.scrollTop
});

console.log(getScrollPosition()); // {x: 0, y: 200}
Copy the code

Checks if the page scrolls to the bottom of the page

Document.documentelement gets the root HTML.

const bottomVisible = () = >
  document.documentElement.clientHeight + window.pageYOffset >=
  (document.documentElement.scrollHeight || document.documentElement.clientHeight);

console.log(bottomVisible()); // true
Copy the code

Checks that all specified elements are visible in the viewport

const elementIsVisibleInViewport = (el) = > {
  const { top, left, bottom, right } = el.getBoundingClientRect();
  const { innerHeight, innerWidth } = window;
  return top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
};

console.log(elementIsVisibleInViewport(el));
Copy the code

Afterword.

Thank you for your patience, this article is the author’s personal learning notes, if there are fallacies, please inform, thank you! If this article is of any help to you, please click on the “like” button. Your support is my motivation to keep updating!