jquery切换弹出窗口然后自动隐藏弹出窗口

时间:2017-03-25 22:01:02

标签: jquery popup

我只想在鼠标点击时切换弹出窗口,然后在几秒钟后自动隐藏弹出窗口。

这是我到目前为止所拥有的。 (这是从w3schools借来的)。此时弹出窗口会在我点击时显示,但除非我再次点击该元素,否则不会消失。怎么才能自动隐藏?

</head>
<body style="text-align:center">

<h2>Popup</h2>

<div class="popup" onclick="myFunction()">Click me to toggle the popup!
  <span class="popuptext" id="myPopup">A Simple Popup!</span>
</div>

<script>
// When the user clicks on div, open the popup
function myFunction() {
    var popup = document.getElementById("myPopup");
    popup.classList.toggle("show");
}
</script>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

您可以使用setTimeout

function myFunction() {
    var popup = document.getElementById("myPopup");
    popup.classList.toggle("show");
    //
    // execute the timeout function after 1 second
    //
    setTimeout(function() {
        document.getElementById("myPopup").classList.toggle("show");
    }, 1000);
}
.popuptext {
    visibility: hidden;
}
.show {
    visibility: visible;
}
<h2>Popup</h2>

<div class="popup" onclick="myFunction()">Click me to toggle the popup!
    <span class="popuptext" id="myPopup">A Simple Popup!</span>
</div>

仅使用CSS transition

function myFunction() {
    var popup = document.getElementById("myPopup");
    popup.classList.toggle("show");
}
.popuptext {
    visibility: hidden;
    opacity: 0;
    transition: visibility 0s 1s, opacity 1s linear;
}
.show {
    visibility: visible;
    opacity: 1;
    transition: opacity 1s linear;
}
<h2>Popup</h2>

<div class="popup" onclick="myFunction()">Click me to toggle the popup!
    <span class="popuptext" id="myPopup">A Simple Popup!</span>
</div>