如何使用数据属性在CSS中设置背景图像? [英] How can I use a data attribute to set a background-image in CSS?
本文介绍了如何使用数据属性在CSS中设置背景图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含几个背景图片(one.jpg,two.jpg,three.jpg)和此标记的文件夹
I have a folder with a few background images (one.jpg, two.jpg, three.jpg) , and this markup
<section class="slide" data-bg="one"></section>
<section class="slide" data-bg="two"></section>
<section class="slide" data-bg="three"></section>
是否可能以某种方式只是使用CSS
.slide{
background-image: url(img/attr(data-bg).jpg);
}
当然这个代码不工作。
推荐答案
这将不可能与纯CSS,除非你是以undynamic的方式:
This won't be possible with pure css unless you're doing it the "undynamic" way:
.slide[data-bg="one"]{
background-image: url('img/one.jpg');
}
.slide[data-bg="two"]{
background-image: url('img/two.jpg');
}
...
也许你可以动态创建你的样式表服务器端的文件名。
Maybe you can dynamically create that stylesheet from your filenames on server-side.
另一个(可能更容易)的可能性是使用JavaScript - 但是因为你排除了我假设你知道这一点,想使用它。
Another (likely easier) possibility is to do this with JavaScript - but since you excluded that I assume you know about that and just don't want to use it.
这篇关于如何使用数据属性在CSS中设置背景图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文