首页 > 解决方案 > 如何使用 setTimeout 和 setInterval 显示 HTML 内容?

问题描述

如何将图像显示几秒钟,然后将其隐藏并显示其余的 HTML 部分。

最初,我想显示图像 2 秒并隐藏 DIV 直到时间。2 秒后隐藏图像并仅显示 div。

我尝试使用 js

setTimeout(() => document.getElementById('Image').style.display = 'block', 2000);
setInterval(() => document.getElementById('Item').style.display = 'none', 2000);
<div id="Image">
  <img src="../img-correct.png" alt="image">
</div>
<div class="item" id="Item">
  <h3>Time:</h3>
</div>

我首先得到 div,然后在 2 秒后得到图像。

标签: javascripthtmlcss

解决方案


Set image display to: 'block' and item display to: 'none' then change both after 2000ms.

const item = document.getElementById('Item');
item.style.display = 'none';

const image = document.getElementById('Image');
image.style.display = 'block';

setTimeout(() => {
  item.style.display = 'block';
  image.style.display = 'none';
}
 ,2000);

推荐阅读