你能帮助我吗?我正在使用脚本来设置已加载的图像,但是样式并未一起应用。

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


我不能在这里放置HTML和CSS样式,因为每个标记都有自定义样式,因此我需要使上面的脚本能够继承样式。

我应该怎么做才能解决这个问题?谢谢

最佳答案

那是因为您正在创建一个新的元素,该元素没有相同的classstyle属性。只需将它们复制到新元素。

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

08-08 04:19