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

如何使用setTimeout实现GIF显示后定时移除类并切换至棕色圆圈

实现点击橙色方块后的序列交互效果

你的需求可以通过以下步骤实现:

  1. 点击橙色方块时,移除方块并显示GIF图
  2. 利用setTimeout设置3秒延迟,之后隐藏GIF并显示棕色圆圈

关键修改说明

  • 调整HTML结构:将棕色圆圈从方块内部移到父容器中,避免方块移除后圆圈被一并删除
  • 优化JS逻辑:明确控制元素的显示/隐藏(而非用toggle),确保状态切换准确
  • 使用setTimeout延迟执行后续操作,参数为延迟时间(毫秒)和要执行的函数

修改后的完整代码

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> gif reveal </title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="parent"> 
        <img class="gif hide" src="kuromi.gif">
        <div id="square"></div>    
        <div class="circle hide_2"></div>
    </div>
    <script src="index.js"></script>
</body>
</html>

CSS

*{
    padding:0;
    margin:0;
}
body{
    background-color:pink;
}
.parent{
    width:100vw;
    height:100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative; /* 添加相对定位,让子元素绝对定位基于父容器 */
}

.gif{
    border-radius: 20px;
    z-index: 1; 
}
.hide{
    display:none;
}
#square{
    width:200px;
    height:200px;
    position: absolute;
    background-color:orange; 
    border-radius: 20px;
    z-index: 2; 
    cursor: pointer;
}

.circle{
    width: 200px;
    height:200px;
    background-color:brown;
    border-radius: 50%;   
    position: absolute;
    z-index: 0;
}

.hide_2{
    display:none;
}

JavaScript

const square = document.getElementById('square');
const gif = document.querySelector('.gif');
const circle = document.querySelector('.circle');

// 点击方块触发的逻辑
square.addEventListener('click', function() {
    // 移除橙色方块
    this.remove();
    // 显示GIF
    gif.classList.remove('hide');
    
    // 3秒后执行切换操作
    setTimeout(() => {
        // 隐藏GIF
        gif.classList.add('hide');
        // 显示棕色圆圈
        circle.classList.remove('hide_2');
    }, 3000); // 3000毫秒 = 3秒
});

代码解释

  • 用addEventListener绑定点击事件,比HTML内联事件更符合现代前端规范
  • setTimeout的第一个参数是要延迟执行的回调函数,第二个参数是延迟的毫秒数
  • 通过添加/移除CSS类来控制元素的显示隐藏,逻辑清晰且易于维护

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 22:53:09