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

求助:如何通过JavaScript实现图片动态显隐并将图片src从HTML迁移至JavaScript文件

Solution: Move Image Source to JavaScript for Dynamic Toggle

Here's how you can refactor your code to move the image src from HTML to JavaScript while maintaining the show/hide toggle functionality:

Step 1: Update the HTML

Remove the src attribute from the <img> tag since we'll set it dynamically via JS:

<div id="image" class="hide">
  <img class="screenshot" width="238" height="222" alt="screenshot" />
</div>
<div id="button"> Click! </div>

Step 2: Adjust the JavaScript

We'll toggle the visibility class and set the image source only when the image is first shown (to avoid unnecessary reloading):

const button = document.querySelector('#button');
const imageContainer = document.querySelector('#image');
const screenshotImg = imageContainer.querySelector('.screenshot');

button.addEventListener('click', () => {
  // Toggle the show/hide class on the container
  imageContainer.classList.toggle('show');
  
  // If we're showing the image, set the src if it hasn't been set yet
  if (imageContainer.classList.contains('show')) {
    if (!screenshotImg.hasAttribute('src')) {
      screenshotImg.setAttribute('src', 'https://picsum.photos/200');
    }
  }
});

Step 3: Keep (or Adjust) Your CSS

Your original CSS using visibility works fine if you want the image's space to remain when hidden. If you prefer to collapse the space when the image is hidden, swap visibility for display:

Original CSS (keeps space when hidden):

#button{
  width: 200px;
  text-align: center;
  padding: 10px;
  font-size: 30px;
  cursor: pointer;
  margin: auto;
}
.hide{
  visibility: hidden;
}
.show{
  visibility: visible;
}

Alternative CSS (collapses space when hidden):

#button{
  width: 200px;
  text-align: center;
  padding: 10px;
  font-size: 30px;
  cursor: pointer;
  margin: auto;
}
.hide{
  display: none;
}
.show{
  display: block;
}

How It Works:

  • The image source is now set exclusively in JavaScript, so it won't appear in your initial HTML markup.
  • We check if the src attribute exists before setting it, ensuring the image is only loaded once (when first revealed) for better performance.
  • The classList.toggle() method handles switching between the hidden and visible states seamlessly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 16:32:34