JavaScript - Get properties of css pseudo element of dom object

window.getComputedStyle(ele,null)

This function can get the displayed properties of the css of the dom object. The second parameter of the function is basically filled with null directly, and this parameter is actually to solve the pseudo element.

window.getComputedStyle(ele,'after');

window.getComputedStyle(ele,'before');

See the following code:

        <div class="demo"> </div>
        <script type="text/javascript">
           var div=document.getElementsByTagName('div')[0];
           
        </script>
.demo{
    width:100px;
    height:100px;
    background-color:red;
    display:inline-block;
}
.demo::after{
    content:"";
    width:10px;
    height:10px;
    display:inline-block;
    background-color:green;
}

I can get the css property of the after pseudo element of the div with the above method

There are more, basically all CSS properties have appeared, this is an array of classes, it satisfies the characteristics of arrays and objects.

Let's see if there are any properties we set.

Indeed they do exist. rgb(0,128,0) is green. It is worth noting that because '-' is not a character recognized by js, this is not an underscore, so it is good to use a small camel case for this.


It is worth noting that the attributes of pseudo elements cannot be changed in this way.

Can only be read, not written.

But I want to change the properties of pseudo-elements.

For example, I click on the red div, and then change the div::after, which is the green one, to orange.

What are you doing?

Change value does not exist.

See the following code:

        <div class="demo" > </div>
        <script type="text/javascript">
           var div=document.getElementsByTagName('div')[0];
           div.onclick=function() {
               div.className='demo1';
           }
        </script>
.demo{
    width:100px;
    height:100px;
    background-color:red;
    display:inline-block;
}
.demo::after{
    content:"";
    width:10px;
    height:10px;
    display:inline-block;
    background-color:green;
}
.demo1{
    width:100px;
    height:100px;
    background-color:red;
    display:inline-block;
}
.demo1::after{
    content:"";
    width:10px;
    height:10px;
    display:inline-block;
    background-color:orange;
}

We changed the class of the div, and then .demo1::after will be automatically selected,

The method is stupid, yet useful.



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325652430&siteId=291194637