简体   繁体   中英

Loading image in background not applying CSS styles

Can you help me? I'm using a script to set the image when it has loaded but the style is not being applied together.

$('img[data-src]').each(function() {
   var img = $(this);
   var newimg = new Image();
   newimg.src = img.attr('data-src');
   newimg.setAttribute('class', img.attr('data-src'));
   newimg.onload = function() {
   img.replaceWith(newimg);
   };
});

I can't put here the HTML & CSS styles because every < img > tag has custom style, so I need make this script above works to inherit styles.

What should I do to solve this issue? Thanks

That's because you are creating a new element which does not have the same class and style attributes. Just copy them to the new element.

$('img[data-src]').each(function() {
   var img = $(this);
   var newimg = new Image();
   newimg.src = img.attr('data-src');
   newimg.setAttribute('class', img.attr('class'));
   newimg.setAttribute('style', img.attr('style'));
   newimg.onload = function() {
   img.replaceWith(newimg);
   };
});

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