如何设置弹出窗口的超时时间?

时间:2019-05-29 10:14:27

标签: javascript html

我创建了一个弹出窗口,当我单击一个按钮时会出现,但是要使其消失,我必须再次单击。 有没有设置计时器并使它消失的方法?

这是代码:

// When the user clicks on div, open the popup
function myFunction() {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");
}
.popuptext {
  display: none;
}
.popuptext.show {
  display: block;
}
<div class="popup" onclick="myFunction()">Click me to toggle the popup!
  <span class="popuptext" id="myPopup">A Simple Popup!</span>
</div>

4 个答案:

答案 0 :(得分:2)

我建议您阅读函数setTimeout() on w3schoolsmozilla dev,这两个函数都是初学者编程的两个好地方。

您的问题可以按照以下代码片段所示的方式解决:

function myFunction() {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");

  if(popup.classList.contains("show")) // Check if the popup is shown
     setTimeout(() => popup.classList.remove("show"), 10000) // If yes hide it after 10000 milliseconds
}

答案 1 :(得分:0)

我将使用setTimeout:

function myFunction(el) {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");
  setTimeout(() => {
    popup.classList.remove("show");
  }, 10000)
}
div {
  display: none;
}

.show {
  display: block !important;
}
<button onclick="myFunction()">Show div below</button>
<br/>
<div id="myPopup">No longer hidden</div>

答案 2 :(得分:0)

<script>
// When the user clicks on div, open the popup
function myFunction() {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");
  
  //Try this, setTimeout takes a callback function to be executed after an amount of time, in this case 3000 milliseconds is 3 seconds
  setTimeout(function(){
    popup.classList.toggle("show");
  },3000)
}
</script>

答案 3 :(得分:0)

这应该有效

function myFunction() {
  var popup = document.getElementById("myPopup");
        document.getElementById("myPopup").style.display= "block"

    setTimeout(function(){ 
    document.getElementById("myPopup").style.display= "none"
   }, 3000);
}