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
- The various methods and differences of obtaining element styles, and which method is most appropriate in which case.
- Element size and position calculations. Got it
client
,scroll
,offset
Differences between the three types of apis. 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
- The style attribute values obtained in this way are humped.
- This method only gets the inline style of the element.
- 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
- The style attribute values obtained in this way are humped.
- Can get all rendered styles of elements including inline or inlined styles.
- 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
- This method can only get element position and size information, not other style information.
- 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
el.className
Gets the element’s class name string. We can use this method to get the class name or add a new class nameel.classList.value
Gets the class name string. If you simply want to get the class name, you can use this method.
conclusion
- We use it when we need to style an element
ele.style
Methods. - This is used when we need to get all the rendered styles of elements
getComputedStyle(ele)
Methods. - The third method can be used when we need to get the class name or batch set the element style.
- 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 element
ele.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
clientWidth
为400px - Scroll bar 15px + left and right inner margins 20 = 405px
clientHeight
为200px - scroll bar 15px + upper and lower inner margins 20 = 205px
clientTop
Is the height of the upper border10px
clientLeft
Is 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.
scrollWidth
为600px + left and right inner margins 20 = 620px
scrollHeight
为500px + inner margin 20 = 520px
clientTop
Is the distance you roll along the y axis10px
clientLeft
Is 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
offsetWidth
为400px - scroll bar 15px + scroll bar 15px + left and right inner margins 20 + left and right border width 20px = 440px
offsetHeight
为200px - scroll bar 15px + scroll bar 15px + top and bottom inner margins 20 + top and bottom border width 20px = 240px
offsetParent
Because nothing else is wrapped around it, I return it directlybody
Elements.offsetTop
becausemargin
for20px
So relative tobody
The vertical offset distance is20px
offsetLeft
becausemargin
for20px
So relative tobody
The 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!