后台加载图片后CSS样式未继承问题求助
Hey there! Let's get this sorted out for you. The core problem in your current script is a simple mistake in how you're copying the class attribute—you're setting the new image's class to the data-src value (the image URL) instead of the original image's actual class names. Plus, there might be other style-related attributes (like inline styles, IDs, or data attributes) that your custom CSS relies on, so we need to make sure those get carried over too.
What's Wrong with the Original Code?
This line is the culprit:
newimg.setAttribute('class', img.attr('data-src'));
You're assigning the image URL (from data-src) as the new image's class, which means it's not inheriting any of the original image's style classes. No wonder your CSS isn't working!
Solution 1: Manually Copy All Style-Related Attributes
If you want to handle it manually, you can copy over the original image's class, inline styles, ID, and any data attributes that your CSS might target:
$('img[data-src]').each(function() { const $originalImg = $(this); const newImg = new Image(); // Copy core style-related attributes from the original image newImg.className = $originalImg.attr('class') || ''; // Copy all class names newImg.style.cssText = $originalImg.attr('style') || ''; // Copy inline styles newImg.id = $originalImg.attr('id') || ''; // Copy ID if present // Copy any data attributes (in case your CSS uses attribute selectors like [data-style]) const originalData = $originalImg.data(); Object.keys(originalData).forEach(key => { newImg.setAttribute(`data-${key}`, originalData[key]); }); // Set the actual image source newImg.src = $originalImg.attr('data-src'); // Replace the original once loaded newImg.onload = function() { $originalImg.replaceWith(newImg); }; });
Solution 2: Use jQuery's clone() for Simplicity
A cleaner approach is to use jQuery's clone() method, which automatically copies all attributes, classes, styles, and even events from the original image. This ensures nothing gets missed:
$('img[data-src]').each(function() { const $originalImg = $(this); // Clone the original image to preserve all its properties const $newImg = $originalImg.clone(); // Replace the original image once the new one loads $newImg.on('load', function() { $originalImg.replaceWith($newImg); }); // Update the src to the actual image URL $newImg.attr('src', $originalImg.attr('data-src')); // Optional: Remove the data-src attribute to avoid reprocessing later $newImg.removeAttr('data-src'); });
Why This Works
- Both methods ensure the new image has all the same class names, inline styles, and attributes that your custom CSS targets.
- The
clone()method is especially useful if your styles rely on less obvious attributes (likedata-*attributes or parent element relationships) because it duplicates the entire element structure.
Give either of these a try—your new images should now pick up all the original styles correctly!
内容的提问来源于stack exchange,提问作者Petr Kann

