如何在HTML列表中适配图片并按CSS指定尺寸显示
Solution to Resize Images and Add Bird Names to List Items
The core issue here is that your dynamically created images aren’t using the .bird-image CSS class you defined, so they’re defaulting to their original size. Additionally, your current code doesn’t include the bird name in each list item as you mentioned. Here’s how to fix both problems:
Modified JavaScript Code
const theList = document.querySelector('.bird-list'); // Ensure you're targeting the correct list element for(let i = 0; i < obj.length; i++){ const item = document.createElement("li"); // Create and configure the image element const img = document.createElement("img"); img.src = obj[i].imagePath; img.classList.add('bird-image'); // Apply your CSS sizing rules to the image // Create and configure the bird name element const birdName = document.createElement("span"); birdName.classList.add('bird-name'); birdName.textContent = obj[i].name; // Replace 'name' with your actual data key if needed // Add both elements to the list item item.appendChild(img); item.appendChild(birdName); theList.appendChild(item); }
Key Changes Explained
- Applied the
.bird-imageclass: This tells the browser to use your predefined CSS styles (50x50px size, rounded border, etc.) for each dynamically generated image. - Added the bird name element: Each list item now includes a styled span for the bird’s name, leveraging your
.bird-nameCSS class for consistent formatting. - Used
constfor variable declarations: This avoids accidental global variable leaks and follows modern JavaScript best practices.
What to Expect After Changes
- Images will display at the 50x50px size specified in your CSS, with the rounded border and other styles you defined.
- Each list item will show both the bird image and its corresponding name, aligned properly thanks to your existing float layout.
- The scrollable list behavior from your
.bird-listCSS will remain intact.
内容的提问来源于stack exchange,提问作者user7041619
相关产品推荐
相关产品推荐

