显示/隐藏图像按钮3秒延迟

Show/Hide image button 3 second delay

本文关键字:3秒 延迟 按钮 图像 隐藏 显示      更新时间:2023-09-26

这是html部分。我在这里所做的是,当用户单击按钮一次时,将调用showIMG函数来显示图像。

<!DOCTYPE html>
<!-- showHide.html
      Uses showHide.js
      Illustrates visibility control of elements
     -->
<html lang = "en">
  <head>
    <title> Visibility control </title>
    <meta charset = "utf-8" />
    <script type = "text/javascript"  src = "showHide.js" >
    </script>
  </head>
  <body>
    <form action = "">
      <div id = "saturn"  style = "position: relative; 
           visibility: visible;">
        <img src = "../images/saturn.png" 
             alt = "(Pictures of Saturn)" />
      </div>
      <p>
        <br />
        <input type = "button"  value = "Toggle Saturn"
               onclick = "flipImag()" />
      </p>
    </form>
  </body>
</html>

javascript文件

// showHide.js
//   Illustrates visibility control of elements
// The event handler function to toggle the visibility 
//    of the images of Saturn 
function flipImag() {
  dom = document.getElementById("saturn").style;  
// Flip the visibility adjective to whatever it is not now 
 if (dom.visibility == "visible")
   dom.visibility = "hidden";
 else
   dom.visibility = "visible";
}

我想在三秒钟内点击一个按钮两次,然后图像消失,当你点击按钮一次,图像出现在屏幕上。我意识到我必须使用切换功能并将其与计时器合并,但我不确定如何做到这一点。

第一次点击设置超时,第二次点击清除超时。

function checkClick(){
    if(window.flippingimage) clearTimeout(window.flippingimage);
    else window.flippingimage = setTimeout(3000, flipImag);
}

然后将此函数放在按钮的onclick事件上。

编辑

将您的代码更改为以下代码:

function flipImag() {
  dom = document.getElementById("saturn").style;  
// Flip the visibility adjective to whatever it is not now 
 if (dom.visibility == "visible")
   dom.visibility = "hidden";
 else
   dom.visibility = "visible";
}
function checkClick(){
    if(window.flippingimage) clearTimeout(window.flippingimage);
    else window.flippingimage = setTimeout(3000, flipImag);
}

和HTML:

<html lang = "en">
  <head>
    <title> Visibility control </title>
    <meta charset = "utf-8" />
    <script type = "text/javascript"  src = "showHide.js" >
    </script>
  </head>
  <body>
    <form action = "">
      <div id = "saturn"  style = "position: relative; 
           visibility: visible;">
        <img src = "../images/saturn.png" 
             alt = "(Pictures of Saturn)" />
      </div>
      <p>
        <br />
        <input type = "button"  value = "Toggle Saturn"
               onclick = "checkClick()" />
      </p>
    </form>
  </body>
</html>