How can I use a data attribute to set a background-image in CSS?

和自甴很熟 提交于 2019-11-27 03:17:15

问题


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>

Would it be possible somehow just with CSS to do something like this?

.slide{
    background-image: url(img/attr(data-bg).jpg);
}

This code isnt working, of course.


回答1:


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.

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.




回答2:


I know the original question stressed doing it with just CSS, but I got to this question because another question (that wasn't necessarily asking for a CSS solution) was marked as a duplicate of this. Here's what I'm using as the solution, in case it helps anyone else, and it uses javascript w/jQuery:

$('.slide').each(function (index) {
    var slide = $(this);
    slide.css('background-image', 'url(' + slide.data('bg') + ')');
});


来源:https://stackoverflow.com/questions/11117915/how-can-i-use-a-data-attribute-to-set-a-background-image-in-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!