如何使用随机计时功能显示/隐藏 div

我想制作一个小故障动画视频。我用了两个视频来解决这个问题。一个完全出问题了,我只想让她通过具有一定时间范围的随机计时功能随机出现或消失。

如何完成或重新编码这一小段 Javascript?

我只需要以随机的隐藏时间进行显示/隐藏...显示最多 5 秒,隐藏在 20 秒到 120 秒之间

请看一下代码:

setTimeout(function(){

        document.getElementById('Video1').style.display = 'none';

    }, 3000); // 10000ms = 10 seconds

<html>

<head></head>

<body>

<div class="Video1" id="Video1" name="Video1">Video1</div>

<div class="Video2" id="Video2" name="Video2">Video2</div>

</body>

</html>


泛舟湖上清波郎朗
浏览 122回答 2
2回答

慕标琳琳

递归将调用 setTimeout 并切换 div 的外观。Video1 将每隔 5 秒播放一次。一旦关闭,它将在 20-120 [s] 间隔内保持这种状态,并且这种情况将无限期地重复。function callTimeout(isOpen, time) {&nbsp; setTimeout(function() {&nbsp; &nbsp; if (isOpen) {&nbsp; &nbsp; &nbsp; document.getElementById('Video1').style.display = 'none';&nbsp; &nbsp; &nbsp; time = (Math.floor(Math.random() * 120) + 20) * 1000;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; document.getElementById('Video1').style.display = '';&nbsp; &nbsp; &nbsp; time = Math.floor(Math.random() * 6) * 1000;&nbsp; &nbsp; }&nbsp; &nbsp; isOpen = !isOpen;&nbsp; &nbsp; callTimeout(isOpen, time);&nbsp; }, time);}callTimeout(true, Math.floor(Math.random() * 6) * 1000)<html>&nbsp; <head></head>&nbsp; <body>&nbsp; &nbsp; <div class="Video1" id="Video1" name="Video1">Video1</div>&nbsp; &nbsp; <div class="Video2" id="Video2" name="Video2">Video2</div>&nbsp; </body></html>

12345678_0001

非常好,非常感谢尤金。我修改了参数以使其更加动态。它太慢了,无法产生故障/无故障效果。&nbsp; &nbsp; &nbsp; &nbsp; function callTimeout(isOpen, time) {&nbsp; setTimeout(function() {&nbsp; &nbsp; if (isOpen) {&nbsp; &nbsp; &nbsp; document.getElementById('Video1').style.display = 'none';&nbsp; &nbsp; &nbsp; time = (Math.floor(Math.random() * 4) + 1) * 1000;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; document.getElementById('Video1').style.display = '';&nbsp; &nbsp; &nbsp; time = Math.floor(Math.random() * 2) * 1000;&nbsp; &nbsp; }&nbsp; &nbsp; isOpen = !isOpen;&nbsp; &nbsp; callTimeout(isOpen, time);&nbsp; }, time);}callTimeout(true, Math.floor(Math.random() * 3) * 1000)<div class="Video1" id="Video1" name="Video1">Video1</div><div class="Video2" id="Video2" name="Video2">Video2</div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript