简体   繁体   中英

CSS: When I change a background-image url() it no longer respects background-size: contain until I resize h&w

I am developing an interface for editing tiles in a Smart Home panel: https://github.com/open-dash/HousePanel

While editing a tile, users will be able to change the background-image of the tile from a library of icons. That is all working, except that when the image is replaced it ignores the background-size: cover for the element in CSS. However, if I change both the height and width it resizes correctly, and I can even set it back to the original size and it stays the right size (see image below.)

Interface - User selects new image in step 2

Because the image is getting replaced, I tried setting the css after the fact, so, in this order:

background-image: url("http://192.168.1.1/icons/toilet.png");
background-size: contain;
-webkit-background-size: contain;
-moz-background-size: contain;
-o-background-size: contain;

...but still I have to change the width and height of the parent div to have it reacalculate/contain to fill the parent div correctly. What gives?

Note: The above are all added via the following code snippet, which works fine otherwise, and I can see the changes when I inspect the element in chrome:

if(sheet.insertRule){
  if(index > -1) {
    sheet.insertRule(selector + "{" + rules + "}", index);        
  }
  else{
    sheet.insertRule(selector + "{" + rules + "}");           
  }
}
else{
  if(index > -1) {
    sheet.addRule(selector, rules, index);    
  }
  else{
    sheet.addRule(selector, rules);   
  }
}

Any thoughts? Is there any way to force it to recalculate the area it needs to fill?

TIA!

If I am correct an on-the-fly stylesheet is created and xhr'd each time?

Have you tried to set the css property directly via jQuery? ( example )

If not, consider triggering a refresh of the element:

document.getElementById(selector).style.display = 'none';
document.getElementById(selector).style.display = 'block';

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