gpt4 book ai didi

javascript - 设置div为隐藏,延时后可见

转载 作者:行者123 更新时间:2023-11-28 05:18:23 25 4
gpt4 key购买 nike

我正在尝试让黄色方 block 在 X 时间后出现在黑色背景上(也许甚至在随机时间之后,但现在让我们只做固定时间)。

function initialSetup() {
if (document.getElementById("yellow") != null) {
document.getElementById('yellow').style.visibility = 'hidden';
setTimeout("document.getElementById('yellow').style.visibility = 'visible'", 2000);
}
.box {
width: 50px;
height: 50px;
}
.yellow {
background: yellow;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
body {
background-color: black;
}
<div id="yellow" class="box yellow"></div>

这段代码最初应该隐藏黄色方 block ,然后在 2 秒后显示出来。但它不起作用。当我尝试使用按钮启动 javascript 功能时,它也不起作用。我查看了其他示例并将我的代码与他们的代码进行了比较,看起来它应该可以工作!

https://jsfiddle.net/xxPoLyGLoTxx/51spg8d1/

最佳答案

首先,您的语法缺少一个。其次,为了遵循最佳实践,您应该为 setTimeout 提供函数引用。您当前的代码将通过 eval() 调用,应不惜一切代价避免这种情况。第三,您需要使用 backgroundColor 而不是 color 来设置元素背景。最后,您不要在任何地方调用 intitialSetup()。考虑到这些问题,试试这个:

function initialSetup() {
if (document.getElementById("yellow") != null) {
document.getElementById('yellow').style.backgroundColor = 'black';
setTimeout(function() {
document.getElementById('yellow').style.backgroundColor = 'yellow'
}, 2000);
}
}

initialSetup();
.box {
width: 50px;
height: 50px;
}
.yellow {
background: yellow;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
body {
background-color: black;
}
<div id="yellow" class="box yellow"></div>

请注意,使用此逻辑,您不会隐藏黄色 div - 正如您的标题所暗示的那样。它只是不是很明显,因为您已经更改了它的背景颜色以匹配 body 的黑色背景。如果要使元素完全不可见,请使用 display 属性。您还可以在 CSS 中设置它以避免在页面加载时出现 FOUC:

function initialSetup() {
if (document.getElementById("yellow") != null) {
setTimeout(function() {
document.getElementById('yellow').style.display = 'block';
}, 2000);
}
}

initialSetup();
.box {
width: 50px;
height: 50px;
}
.yellow {
background: yellow;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: none;
}
body {
background-color: black;
}
<div id="yellow" class="box yellow"></div>

最后,这是上述问题的 jQuery 实现,因为您已将问题标记为:

$(function() {
setTimeout(function() {
$('#yellow').show()
}, 2000);
});
.box {
width: 50px;
height: 50px;
}
.yellow {
background: yellow;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: none;
}
body {
background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="yellow" class="box yellow"></div>

关于javascript - 设置div为隐藏,延时后可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42228423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com