CSS设置background-image由data-image attr [英] CSS set background-image by data-image attr
问题描述
我有这种模式的元素:
< div data-image ={imageurl}。 。>< / div>
我想设置此元素 background-image
到 data-image
。我测试这个CSS代码:
div [data-image] {
border:2px solid black;
background-image:attr(data-image url);
}
边框显示正确但没有发生背景
我如何修复此代码只与css(不是js或jq)?
http://dev.w3.org/csswg/css-values/#attr-notation> attr()
符号,而不是 content
- 如 background-image
- 是
此外,根据 CSS第2级规范,结合了 url()
和 attr()
无效:
。 content:url(attr(data-image));
因此,目前没有跨浏览器的CSS解决方案来实现所需的结果。除非使用JavaScript是一个选项:
var list = document.querySelectorAll(div [data-image]); for(var i = 0; i
div [data-image] {width:100px; height:100px; / *如果需要* / border:2px solid black;}
< div data-image =http://placehold.it/100>< / div>
p>
I have sort of elements with this pattern:
<div data-image="{imageurl}" ...></div>
I want to set this elements background-image
to data-image
. I test this CSS code:
div[data-image] {
border: 2px solid black;
background-image: attr(data-image url);
}
border show correctly but nothing happened for background How can do I fix this code only with css (not js or jq)?
As of writing, the browser support of attr()
notation on CSS properties other than content
- like background-image
- is very limited.
Besides, as per CSS level 2 spec, combining url()
and attr()
is not valid:
.content: url(attr(data-image));
Hence there is no cross-browser CSS solution at the moment to achieve the desired result. Unless using JavaScript is an option:
var list = document.querySelectorAll("div[data-image]");
for (var i = 0; i < list.length; i++) {
var url = list[i].getAttribute('data-image');
list[i].style.backgroundImage="url('" + url + "')";
}
div[data-image] {
width: 100px; height: 100px; /* If needed */
border: 2px solid black;
}
<div data-image="http://placehold.it/100"></div>
这篇关于CSS设置background-image由data-image attr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!