简体   繁体   English

显示图像,5秒后将其隐藏,然后出现一个按钮以显示下一张图像

[英]Show image, hide it after 5 seconds and a button comes up to show next image

For school I want to make an webpage, where I show 1 image, which disappears after 5 seconds and a button appears. 对于学校,我想制作一个网页,其中显示1张图像,该图像在5秒钟后消失并显示一个按钮。 You have to push the button before the next image shows up which shows then for 5 seconds. 您必须按下按钮才能显示下一个图像,然后显示5秒钟。 So the same story every time. 每次都是一样的故事。

As I know a little about coding I found some piece of code here and tried to use it, but I can only let 1 image show for 5 seconds after I push the button. 据我对编码的一点了解,我在这里找到了一些代码并尝试使用它,但是按下按钮后,我只能让1张图片显示5秒钟。

Here is the code 这是代码

<input type="button" value="Show image for 5 seconds" onclick="show()"><br><br>
<div id="myDiv" style="display:none"><img id="1" src="img/logo.png"></div>
<div id="myDiv" style="display:none"><img id="2" src="img/test.jpg"></div><br>
<script type="text/javascript">
    function show() {
        document.getElementById("myDiv").style.display = "block";
        setTimeout("hide()", 5000);  // 5 seconds
    }
    function hide() {
        document.getElementById("myDiv").style.display = "none";
    }
</script>

Thanks and I hope you guys can help me out! 谢谢,我希望你们能帮助我! :) :)

Well, for starters, you've got two divs with the same id, which is incorrect. 好吧,对于初学者来说,您有两个具有相同ID的div,这是不正确的。 Assuming you've got your images like this: 假设您的图像是这样的:

<button id="next" onclick="showNext();">Show next image</button><br />
<div class="image" style="display: none;"><img src="img/logo1.png" /></div>
<div class="image" style="display: none;"><img src="img/logo2.png" /></div>
<div class="image" style="display: none;"><img src="img/logo3.png" /></div>
<div class="image" style="display: none;"><img src="img/logo4.png" /></div>

<script type="text/javascript">
    var divs = document.querySelectorAll('div.image'); //select all divs with class 'image'
    var button = document.getElementById('next'); //button.
    var currentImage = 0;
    function showNext() {
        button.style.display = 'inline';
        divs[currentImage].style.display = 'block';
        setTimeout(hide, 5000);
    }

    function hide() {
        button.style.display = 'block';
        divs[currentImage].style.display = 'none';
        currentImage = (currentImage + 1) % divs.length;
    }
</script>

I didn't bother with styling your elements with CSS rules, which would be recommendable, but this would work as intended. 我不喜欢使用CSS规则来设置元素的样式,这是值得推荐的,但这可以按预期工作。

删除双引号:

setTimeout(hide, 5000);  // 5 seconds

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM