2013-11-29 76 views
0

代碼:得到更多的元素屬性costum

<div id="gallery" data-image="img_folder/g1.jpg"></div> 
<div id="gallery" data-image="img_folder/g2.jpg"></div> 
<div id="gallery" data-image="img_folder/g3.jpg"></div> 
<div id="gallery" data-image="img_folder/g4.jpg"></div> 
<div id="gallery" data-image="img_folder/g5.jpg"></div> 

CSS:

<style type="text/css"> 
#gallery { width:100px; height:100px; background-size:cover; } 
</style> 

的jQuery:

var el = $("#gallery"); 
var img = el.attr("data-image"); 

for(i=0; i<=el.length; i++) { 
    el.css({ "backgroundImage": "url("+img+")" }); 
} 

但是,圖像不顯示到div的,沒有成功的任何想法???

+1

的ID應該是唯一的.. –

+0

即使'el'包含多個元素,請注意'.attr':*「獲取匹配元素集合中**第一個元素**的屬性值。」* (http://api.jquery.com/attr/)閱讀文檔確實有幫助,你應該試試看! –

+0

okey thanks @felix ... – Ryo

回答

1

元素的第一個ID必須是唯一的,使用類

<div class="gallery" data-image="img_folder/g1.jpg"></div> 
<div class="gallery" data-image="img_folder/g2.jpg"></div> 
<div class="gallery" data-image="img_folder/g3.jpg"></div> 
<div class="gallery" data-image="img_folder/g4.jpg"></div> 
<div class="gallery" data-image="img_folder/g5.jpg"></div> 

.gallery { width:100px; height:100px; background-size:cover; } 

然後

$('.gallery').css('backgroundImage', function(){ 
    return 'url(' + $(this).data('image') + ')'; 
}) 

演示:Fiddle

+0

哇...謝謝@arun的回答..它的工作...... :) – Ryo