2015-05-09 89 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,其實我也沒有在這件事上找到任何答案......沒問題,不客氣 –