简体   繁体   中英

Can I Get CSS Image Rule in JavaScript?

I want to get an css image rule, like (URL, Size) in JavaScript such as Variable.

Example Show:

- HTML Right Syntax:

<div id="mydiv"></div>

- CSS Right Syntax:

<style>
body{
background: url('a.png');
background-image-size: cover;
}
</style>

JS Error Syntax:

    <script>
      function GetImgVar(){
       var imgsrc = document.body.style.backgroundImage;
         document.getElementById('mydiv').style.backgroundImage=imgsrc;
       }
    </script>

Yes, you can. Try it:

<style id="stylesheet1">
body{
background: url('a.png');
background-image-size: cover;
}
</style>

<script>
var sheet = document.querySelector('#stylesheet1').sheet;

console.log(sheet.cssRules);// This will print all css rules that belongs to the body tag;

</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM