You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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-image class: 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-name CSS class for consistent formatting.
  • Used const for 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-list CSS will remain intact.

内容的提问来源于stack exchange,提问作者user7041619

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:44:48