2015-05-09 90 views
2

我已经在多个div上使用CSS背景来创建一些大型格式按钮。它看起来很漂亮,但按钮是动态创建的,可能有成千上万个按钮。这意味着一个巨大的动态CSS脚本......它有一个更好的方式给每个元素一个不同的CSS背景具有相同的属性?更改背景元素与多个背景图片

这里是示例代码 - HTML:

<div id="ab_a" class="banner_button">   
    <h2>Title A</h2>` 
</div> 

<div id="ab_b" class="banner_button">  
    <h2>Title B</h2>` 
</div> 

<div id="ab_c" class="banner_button">   
    <h2>Title C</h2>` 
</div> 

等等......(有可能是这几千个)

的CSS:

#ab_a { 
     background: 
    linear-gradient(
     rgba(0, 0, 0, 0.0), 
     rgba(0, 0, 0, 0.6) 
    ), 
    url(../images/bgimageA.jpg); 
    background-size: cover; 
    width: 100%; 
    padding-bottom:37.01%; 
    position: relative; 
    float: left; 
} 
#ab_b { 
     background: 
    linear-gradient(
     rgba(0, 0, 0, 0.0), 
     rgba(0, 0, 0, 0.6) 
    ), 
    url(../images/bgimageB.jpg); 
    background-size: cover; 
    width: 100%; 
    padding-bottom:37.01%; 
    position: relative; 
    float: left; 
} 
#ab_c { 
     background: 
    linear-gradient(
     rgba(0, 0, 0, 0.0), 
     rgba(0, 0, 0, 0.6) 
    ), 
    url(../images/bgimageC.jpg); 
    background-size: cover; 
    width: 100%; 
    padding-bottom:37.01%; 
    position: relative; 
    float: left; 
} 

...我不想在动态CSS文件中重复这段代码1000次。

如何从后面的代码中分离后台url(唯一改变的位)?

顺便说一句 - 在脚本中只放入后台网址将不起作用,它将忽略样式表中的所有CSS属性。

在此先感谢。

+0

是的..只是得到了。 –

回答

1

单个元件上的使用多个背景图像,不幸的是,没有办法使用纯CSS设置在一个单独的规则第二背景图像而不重复所有先前的背景层

jQuery来拯救。
jsFiddle demo in action

里面你的CSS设置第二个背景none

.banner_button{ 

    background: linear-gradient(
     rgba(0, 0, 0, 0.0), 
     rgba(0, 0, 0, 0.6) 
    ), none 50%/cover; /* notice the `none` for the second layer */ 

    width: 100%; 
    padding-bottom: 37.01%; 
    position: relative; 
    float: left; 
} 

而创建的元素,确保生成它们通过从你使用的任何数据所需的图像URL,> >在你生成的元素的data-*属性中:

<div class="banner_button" data-bg="../images/whatever.jpg"></div> 

比使用jQuery,由data-bg属性holded者值替换none值:

$(".banner_button").css("backgroundImage", function(i, v){ 
    return v.replace("none", "url("+ $(this).data("bg") +")"); 
}); 

就是这样。
jQuery将为您重建整个背景图层!

+0

天才!这正是我需要的解决方案!我很惊讶我无法在StackOverflow上的其他任何地方找到它,可能会认为这些日子会非常普遍。完美的作品。非常感谢! – Leon

+0

@Leon,其实我也没有在这件事上找到任何答案......没问题,不客气 –