js knowledge points: usage of getComputedStyle, js method to obtain dom style

There are two ways to obtain DOM styles: the first is inline style and the second is other styles.

1. Obtaining inline styles is relatively simple. Generally, the style can be obtained through element.style.attr.

<template>
 <div id="demo"></div>
<template>
<script>
     var dom = document.getElementById('demo')
     console.log(dom.style.width) // 300px
</script>

2. Other styles. Here we take the class style as an example.

<template>
 <div class="box"></div>
 <div class="box"></div>
<template>
<script>
     var dom = document.getElementsByClassName('box')[1]
     getComputedStyle(dom,null)['color']   //red
</script>
<style>
.box {
 width: 200px;
 height: 200px;
 color: red;
</style>
Summary of js knowledge points: usage of getComputedStyle

getComputedStyle is a method that can get all the final CSS property values ​​of the current element; getComputedStyle() is a method that can get the current style of the element;

This method is a window method and can be used directly

Requires two parameters

  • The first: the element to get the style
  • Second: You can pass a pseudo element, usually null

This method will return an object, which encapsulates the style corresponding to the current element.

1. You can   read the style in the form of getComputedStyle(object, null). style name

If the obtained style is not set, the real value will be obtained instead of the default value.

For example: if width is not set, it will not get auto, but a length

2. For more convenient use, you can add regular expressions to obtain the style name.

Use  the form getComputedStyle(style element, null)[style name]  to get the style

Supplement: The difference between getComputedStyle and style

We can also get the CSS style declaration object of the element using element.style, but there are some differences between it and the getComputedStyle method (read-only and writable).

1. As mentioned above, the getComputedStyle method is read-only and can only obtain the style but cannot set it; element.style can be read, written, and flexible.

2. The obtained object scope getComputedStyle method obtains all CSS attribute objects that are finally applied to the element (even if there is no CSS code, the default eight generations of ancestors will be displayed);

Element.style can only get the CSS style in the element's style attribute. So for a bare element <p>, the getComputedStyle method returns the value of the length attribute in the object

(If any) is 190+, and element.style is 0.

Guess you like

Origin blog.csdn.net/weixin_51747462/article/details/133084690