【问题标题】:How to show image for 3 seconds on every button click? [closed]如何在每次单击按钮时显示 3 秒的图像? [关闭]
【发布时间】:2021-03-17 06:17:34
【问题描述】:

我有一个 HTML/js 代码,点击按钮时我会显示一张图片。我写了以下内容:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>title</title>
    <script type="text/javascript" src="source here"></script>
    <script type="text/javascript">
        let pictures = [array of pics here];
        function show() {
            let index = randInt(0, words.length - 1);
            document.getElementById("picture").src = "images/" + pictures[index] + ".jpg";

        }
        function hide() {
            window.setTimeout("document.getElementById('picture').style.display='none';", 3000);

        }
    </script>
</head>
<body>

这会使图像消失,但是当我再次单击该按钮时,图像不会显示。该功能是否永久隐藏图像?我怎样才能使它每按一次按钮,图像就会显示 3 秒钟然后消失?感谢您的帮助。

【问题讨论】:

  • 这段代码在 3 秒后隐藏了一个 ID 为 picture 的元素。你的意思是做别的事吗?
  • 欢迎来到 Stack Overflow!请发布minimal reproducible example。您可以使用Stack Snippet 使其可执行。
  • 首先,您提供了不完整的代码,我想您对应的 show 函数未设置为正确删除 display=none 样式。其次,setTimeout 接受一个函数,而不是一个字符串。
  • @junvar 它也接受一个字符串,它会用eval() 执行它。
  • @Clome document.getElementById('picture').style.display = 'block'?

标签: javascript html image


【解决方案1】:
    function show() {
        let index = randInt(0, pictures.length - 1);
        let pic = document.getElementById("picture");
        pic.src = "images/" + pictures[index] + ".jpg";
        pic.style.display = 'block';
        window.setTimeout("document.getElementById('picture').style.display='none';", 3000);
    }
    // delete your hide() function

【讨论】:

  • 非常感谢!您能否解释一下您的最后一行与其他所有内容有关的内容?
  • 更具体地说,我的超时功能是如何在按钮单击时失效的?
  • 最后一行pic.style.display = 'block';取消隐藏被display='none'隐藏的图片
  • 经过进一步思考,您需要将 hide() 函数滚动到 show() 函数的末尾。所以,显示图像,然后设置一个计时器来隐藏它。我在上面编辑我的代码。
猜你喜欢
  • 2014-10-03
  • 2012-03-22
  • 1970-01-01
  • 2012-02-16
  • 2017-02-16
  • 2012-04-28
  • 1970-01-01
  • 2022-12-21
相关资源
最近更新 更多