【发布时间】:2026-01-11 11:25:01
【问题描述】:
我遇到的问题是,我在 JavaScript 中创建的 onclick 函数只能在每次单击按钮时执行。添加此代码后发生这种情况(因为我想在 x 秒后隐藏类/div):
popup.classList.toggle("show");
setTimeout(
function() {
popup.classList.toggle("hide");
}, 750);
}
换句话说,它在第一次单击时起作用,然后当类显示 x 秒时,当我再次单击它时。什么都没有发生,但是在下一次单击时它会起作用。这种情况一直在继续。有什么问题?
我尝试复制代码,但它在 jsfiddle 中似乎不像在项目中那样工作。如果有人能告诉我这段代码有什么问题,以及如何让它在每次单击按钮时显示弹出窗口。
https://jsfiddle.net/xxuvwc1b/
function showpop() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
setTimeout(
function() {
popup.classList.toggle("hide");
}, 750);
}
.popup {
background-color: black;
position: relative;
display: inline-block;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
font-weight: bold;
font-family: 'Raleway', sans-serif;
font-size: 1em;
text-decoration: none;
color: green;
float: left;
border-radius: 5px;
border: none;
width: 100%;
}
:focus {
outline: 0 !important;
}
.popup .popuptext {
visibility: hidden;
width: 160px;
background-color: #555;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 8px 0;
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
margin-left: -80px;
}
/* Popup arrow */
.popup .popuptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
.popup .show {
visibility: visible;
-webkit-animation: fadeIn 1s;
animation: fadeIn 1s;
}
.popup .hide {
visibility: hidden;
}
@-webkit-keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
<button class="popup" onclick="showpop();"><span class="popuptext" id="myPopup">HERE I AM!</span>SHOW ME A POPUP</button>
【问题讨论】:
-
当我切换它时,它不起作用。
-
小提琴没有奏效是因为:*.com/questions/5431351/…
标签: javascript html css function settimeout