【发布时间】:2019-12-08 13:15:16
【问题描述】:
我正在尝试通过 html 标签上定义的属性中的 css 动态分配 background-image 的 url。但似乎attr() 和var() 都不起作用。我避免使用 javascript,因为 url 稍后可能会更改,所以我必须再次手动触发该脚本。
有没有更好的解决方案?
body {
display: flex;
}
.normal, .attr, .var {
flex: 1;
height: 240px;
border: solid 1px #666;
background-size: cover;
}
.normal {
background-image: url("https://picsum.photos/320/240");
}
.attr {
background-image: url(attr(data-bg));
}
.var {
background-image: url(var(--url));
}
<div class="normal"></div>
<div class="attr" data-bg="https://picsum.photos/320/240"></div>
<div class="var" style="--url: 'https://picsum.photos/320/240';"></div>
如果可能的话,我希望我可以连接字符串。
.image {
border: solid 1px #666;
width: 320px;
height: 240px;
/* I wish this is possible */
background-image: url("http://www.example.com/images/" attr(data-bg) ".png");
}
<div class="image" data-bg="adorable_cat"></div>
【问题讨论】:
标签: html css css-variables