2014-12-27 217 views
1

我有一個小問題,我想從數據屬性中獲取「路徑」並添加到背景。jQuery從數據屬性獲取路徑

HTML

<div> 
    <div data-image="../images/header.jpg"></div> 
</div> 

jQuery的

$('[data-image]').css(
    { 
     background: "url("+$(this).data('image')+") no-repeat center", 
     backgroundSize: "cover", 
     height: ($(document).height()/ 3) 
    } 
); 

你有任何想法如何做到這一點?

+0

是否有與數據屬性超過一個元素?如果是這樣,請使用'each' – adeneo 2014-12-27 14:05:30

回答

2

只是緩存元素的一個變量,並使用它

var elm = $('[data-image]'); // cache it 
elm.css({ 
    background: "url("+ elm.data('image') +") no-repeat center", // use it 
    backgroundSize: "cover", 
    height: ($(document).height()/ 3) 
}); 

如果有更多的元素,你可以使用each

elm.each(function(){ 
    $(this).css({ 
     background: "url("+ $(this).data('image')+ ") no-repeat center", 
     backgroundSize: "cover", 
     height: ($(document).height()/ 3) 
    }); 
});