简体   繁体   中英

Add background image to a div via javascript

<div class="splash-image-wrap splash-image">
<img class="splash-image-bg" src="http://mysite-com/image.jpg" alt="image-bg">
</div>

Can you help me with a script that adds the img src url as image background for the wrap div?

I'm trying this but does not work

$(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();
});
});

You want to keep things that are static in your css file, such as background-size and 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;
}

Also as a sidenote, you do not need window.load or document.ready in your code after you have wrapped it like $(function(){}) .

window.load is used for waiting for inner frames and images to load. Since you haven't injected your background image yet, you do not need to wait for this to run your code.

Also, document.ready is equivalent to wrapping your function like $(function() { , which you are already doing. You can completely scrap these and have it still work.

Assuming you're loading the jQuery library, the following should work:

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

If not, you'd need to rewrite your function using vanilla JS.

You have the correct code, however not sure why you have a $(window).load . Here is a working version

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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM