通过javascript将背景图像添加到div

时间:2015-10-13 07:50:30

标签: javascript background-image

<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添加为wrap 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();
});
});

3 个答案:

答案 0 :(得分:2)

您希望在css文件中保留静态内容,例如background-size和background-position。

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.load包裹起来后,代码中不需要document.ready$(function(){})

window.load用于等待内部帧和图像加载。由于您尚未注入背景图像,因此无需等待此操作即可运行代码。

此外,document.ready相当于将您的功能包裹起来$(function() {,您已经在做了。您可以完全废弃这些并使其仍然有效。

答案 1 :(得分:0)

假设您正在加载jQuery库,以下内容应该有效:

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

如果没有,你需要使用vanilla JS重写你的函数。

答案 2 :(得分: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();
});