简体   繁体   中英

How to change Divs CSS Background given in the attribute on page Load “jquery”

so basically I am having this problem where I want jQuery to check the class .js-bg in the attribute: "data-background" , get the attribute and then change that divs css Background to the url given in the attribute.

HTML:

<div class="js-bg">
    <br><br><br><br>
</div>

CSS:

.js-bg {
    width: 100%;
    background-size: cover;
    background-position: center;
}

JS/jQuery (first try):

var item = $('.js-bg'),
    bg = item.attr('data-background');

item.css('background', 'url(' + bg + ')');

The Problem here is that it takes the first Attribute and then applied that image to all of the rest Divs.

JS/jQuery (Second try):

var item = $('.js-bg'),
    bg = item.attr('data-background');

item.load(function() {
    $(this).css('background', 'url(' + bg + ')');
});

But this doesn't work aswell, I have searched all over the internet, but couldn't find an answer.

Thank you for your consideration.

Try to loop trough those elements and set background for each one like this:

$('.js-bg').each(function(){

  var bg=$(this).attr('data-background');
  $(this).css('background', 'url('+ bg +')');

}); 

If you have multiple divs with the same class, the $('.js-bg') will take all of them and replace the background on all of them.

If you only want to change one of them, you should have a unique selector on the div you wish the background changed.

$(this) will only work if something inside that element triggers the background change.

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