【问题标题】:How do I make a div appear and to disappear on a webpage?如何让 div 在网页上出现和消失?
【发布时间】:2021-08-19 18:49:32
【问题描述】:

我试图让一个 div 在网站上显示 1 分钟,然后消失 9 分钟,然后循环重复。

我想使用下面的东西,而不是使用 setTimeout()。


        //gets the current time. 
var d = new Date();
if(d.getHours() >= 7 && d.getHours() <= 15 ){
    $(".open").show();
    $(".closed").hide();
}
else {  
     $(".closed").show();
    $(".open").hide();
}

因此,div 将每隔 10 分钟显示一次,因此在 00:00、00:10、00:20、00:30、00:40、00:50 每小时过去 1 分钟及之后这分钟 div 会自动在网页上消失 9 分钟。

这可能吗?

【问题讨论】:

  • 如果不使用setTimeout()setInterval(),什么会触发代码再次运行?
  • 你为什么不想使用setTimeout()
  • 对不起,我想要它,所以您不能只是刷新页面来重置进程并立即显示 div。我想要它,所以 div 每 10 分钟显示一次,但基于实时
  • 当页面加载时,检查当前时间并计算超时时间。

标签: javascript html jquery css time


【解决方案1】:

let timer;


let interval = 3000;
//You can change interval to your desireable MILLISECONDS
let showTime = 500;
//change this for div showing time
//Each div will show for 100 ms

let mainTimer = (60 - (new Date().getMinutes())) * 60000;



$(".divI").hide();
setTimeout(function() {
  let counter = true;
  htmlTimer();

  //runs function every 'interval' MS
  setInterval(function() {
    htmlTimer();
    $(".divII").hide();
    $(".divI").show();
    //hides main content div and shows close div every 'showTime' ms
    setTimeout(function() {
      htmlTimer();
      $(".divII").show();
      $(".divI").hide();
    }, showTime);
  }, interval);

}, mainTimer);




function htmlTimer() {
  clearTimeout(timer);
  let count = 0;
  timer = setInterval(function() {
    count++;
    $('.timer').html((count * 200) + 'ms');
  }, 200);
}



let remaingTime = setInterval(function() {

  mainTimer = mainTimer - 200;
  $('.currentTime').html(new Date().toString());

  $('.remainingTime').html('Remaining Time:' + (mainTimer / 60000).toFixed(1) + 'Mins');
}, 200);

setTimeout(function() {
  clearTimeout(remaingTime);
  $('.currentTime').html('');
  $('.remainingTime').html('');
}, mainTimer)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='divI'>Div-1--mainContent</div>
<div class='divII'>Div-2--closeDiv</div>
<br>
<div class='timer'></div>
<div class='currentTime'></div>
<div class='remainingTime'></div>

【讨论】:

  • 如何同步到小时后的 :10、:20、:30 等分钟?
  • 这只是交替隐藏和显示每个间隔,它不显示 1 分钟并隐藏接下来的 9 分钟。
  • 如果您需要在特定时间运行的函数通知,我只与分钟同步
  • 谢谢,我会用这段代码,谢谢
猜你喜欢
  • 2011-03-12
  • 1970-01-01
  • 2014-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-22
相关资源
最近更新 更多