我想显示div几秒钟,所以我进行了编码:
.SetPreference
,但几秒钟后它不会隐藏。我该如何解决?
如果我要让这个div在所有页面(其他div)的前面几秒钟?
答案 0 :(得分:0)
您的display
函数当前正在做什么,等待1000
毫秒并调用alertFunc
,这只是更改元素的innerText
(这可能正在显示它(如果之前是空的),但那里什么也没有被隐藏。
假设您只需要显示/隐藏一个元素,则应该执行以下操作:
const popup = document.getElementById('popup');
let timeoutID = null;
function showPopup(text, duration) {
// In case we called this before:
clearTimeout(timeoutID);
// Update the text and show:
popup.innerText = text;
popup.classList.remove('hidden');
if (duration) {
// After `duration` ms, call hidePopup to hide it again:
timeoutID = setTimeout(hidePopup, duration);
}
}
function hidePopup() {
popup.classList.add('hidden');
}
showPopup(' Hello there!', 1000);
document.onclick = () => {
showPopup(' Hello there!', 1000);
};
body {
font-family: monospace;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
user-select: none;
}
#popup {
position: fixed;
top: 50%;
left: 50%;
height: 160px;
width: 300px;
margin: -80px 0 0 -150px;
background: white;
box-shadow: 0 0 32px 0 rgba(0, 0, 0, .125);
border-radius: 2px;
display: flex;
justify-content: center;
align-items: center;
}
#popup.hidden {
display: none;
}
Click anywhere to display the popup again.
<div id="popup" class="hidden"></div>
答案 1 :(得分:0)
如果您只想使用display
函数查看div 1秒钟(1000毫秒),则可以执行以下操作:
function display() {
document.getElementById("theDiv").style.display = "none";
setTimeout(() => document.getElementById("theDiv").style.display = "block", 1000);
}
答案 2 :(得分:0)
只是建议稍作更正,而不是对代码进行整体改编。
var myVar;
function display() {
myVar = setTimeout(alertFunc, 1000);
}
function alertFunc() {
//hiding now
document.getElementById('random').style.display = 'none';
}