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

如何实现每60秒交替隐藏显示container、container2两个div

问题原因

你的代码无法循环切换的核心原因是定时器内的逻辑是固定执行「隐藏container、显示container2」的操作,每次触发都执行相同的赋值,自然不会切回原来的状态。


解决代码

你只需要修改JS部分的逻辑,添加一个状态标记记录当前显示的元素,每次定时器触发时反向切换状态即可,原有CSS代码不需要做任何改动:

window.onload = function() {
  // 状态标记,初始为true代表当前显示container
  let isContainerActive = true
  setInterval(function() {
    if (isContainerActive) {
      document.getElementById('container').style.display = 'none'
      document.getElementById('container2').style.display = 'flex'
    } else {
      document.getElementById('container').style.display = 'flex'
      document.getElementById('container2').style.display = 'none'
    }
    // 翻转状态标记
    isContainerActive = !isContainerActive
  }, 60000)
  // 测试演示时可以把上面的60000改成5000,实现5秒切换一次
}

如果想要更精简的写法,也可以直接读取元素当前的显示状态做判断,不需要额外声明状态变量:

window.onload = function() {
  setInterval(function() {
    const cont1 = document.getElementById('container')
    const cont2 = document.getElementById('container2')
    const cont1IsShow = cont1.style.display === '' || cont1.style.display === 'flex'
    cont1.style.display = cont1IsShow ? 'none' : 'flex'
    cont2.style.display = cont1IsShow ? 'flex' : 'none'
  }, 60000)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 07:06:00