2015-10-13 70 views
1
<div class="splash-image-wrap splash-image"> 
<img class="splash-image-bg" src="http://mysite-com/image.jpg" alt="image-bg"> 
</div> 

你能幫我一個添加img src url作爲圖像背景的包裝div的腳本嗎?通過javascript將背景圖像添加到div

我想這一點,但不起作用

$(function() { 

function updatePageForTopImg(){ 
    // background image using size cover 
    // top background image 
    $('.splash-image-wrap').css('background-image', 'url('+$(".splash-image-bg").attr("src")+')').css('background-size' , 'cover').css('background-position' , 'top center'); 
} 
$(window).on('load', function(){ 
updatePageForTopImg(); 
}); 
}); 
+1

可能重複[如何更改div的背景圖像使用JavaScript?](http://stackoverflow.com/questions/21496905/how-to-change-the-background-image-of-div-using- javascript) –

+1

如何在純CSS中做到這一點?正如我在你的代碼中看到的那樣,你的圖像的src已經變成了aviable。如果你希望能夠打開或關閉背景,你應該實現代表兩個切換狀態的CSS規則。通過JS應用大量的CSS是一種不好的做法。 –

回答

0

假設你正在加載jQuery庫,下面應該工作:

$('.splash-image-wrap').css({ 
    'background-image': 'url(" + $('.splash-image-bg').attr('src') + ")', 
    'background-size': 'cover', 
    'background-position': 'top center' 
}); 

如果沒有,你需要重寫你的功能使用香草JS。

0

你有正確的代碼,但不知道爲什麼你有一個$(window).load。 這裏是一個工作版本

的jsfiddle:https://jsfiddle.net/CanvasCode/rn7ejrke/1/

jQuery的

function updatePageForTopImg() { 
     // background image using size cover 
     // top background image 
     $('.splash-image-wrap') 
      .css('background-image', 'url(' + $(".splash-image-bg").attr("src") + ')') 
      .css('background-size', 'cover') 
      .css('background-position', 'top center'); 
    } 

$(function() { 
    updatePageForTopImg(); 
}); 
2

你想保留的東西,在你的CSS文件是靜態的,如背景,規模和背景的位置。

JS:

$('.splash-image-wrap').css({ 
    background-image: 'url(" + $('.splash-image-bg').attr('src') + ")' 
}); 

CSS:

.splash-image-bg { 
    background-size: cover; 
    background-position: center top; 
} 

另外,作爲一個旁註,你不需要window.loaddocument.ready在你的代碼你已經把它包像$(function(){})後。

window.load用於等待內部幀和圖像加載。既然你還沒有注入你的背景圖片,你不需要等待它來運行你的代碼。

另外,document.ready相當於包裝你的功能,如你已經在做的$(function() {。你可以完全取消這些並使其仍然有效。

+0

準確答案!刪除了我的帖子;)沒有在'(function(){})'+1前面實現'$' – Martin