CSS:当我更改背景图像url()时,它不再尊重背景大小:包含直到我调整大小h& w

时间:2018-01-10 19:25:50

标签: javascript php jquery css

我正在开发一个用于在智能家居面板中编辑图块的界面:https://github.com/open-dash/HousePanel

在编辑图块时,用户可以从图标库中更改图块的背景图像。这一切都有效,除了当替换图像时,它忽略了CSS中元素的background-size:cover。但是,如果我更改高度和宽度,它会正确调整大小,我甚至可以将其设置回原始大小并保持正确的大小(请参见下图。)

Interface - User selects new image in step 2

因为图像正在被替换,我尝试在事后设置css,因此,按此顺序:

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;

...但我仍然需要更改父div的宽度和高度,以使其重新计算/包含以正确填充父div。是什么给了什么?

注意:上面的代码片段都是通过以下代码片段添加的,否则可以正常工作,当我检查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);   
  }
}

有什么想法?有没有办法强迫它重新计算它需要填充的区域?

TIA!

1 个答案:

答案 0 :(得分:0)

如果我是正确的,每次都会创建动态样式表并且xhr' d?

您是否尝试过通过jQuery直接设置css属性? (example

如果没有,请考虑触发元素的刷新:

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