我想隐藏一个元素,并在一秒钟后显示一个新元素,
这是简化的代码:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
function loadNewSubmenu()
{
document.getElementById("content-1").className = "hide-part";
sleep(1000);
document.getElementById("content-2").className = "show-part";
}
.hide-part{
display : none;
}
<button id="content-1" class="show-part">B1</button>
<button id="content-2" class="hide-part">B2</button>
<button onclick="loadNewSubmenu()">click me</button>
我的期望:
#content-1
#content-2
但这就是我得到的:
#content-1
已更改#content-2
已更改我知道我可以使用setTimeout
来修复它,但这种行为背后的原因是什么?
答案 0 :(得分:1)
你可以使用setTimeout();
这是一个例子:`
<script>
function loadNewSubmenu()
{
document.getElementById("content-1").className = "hide-part";
setTimeout(function(){
document.getElementById("content-2").className = "show-part";
},1000);
}
</script>`
答案 1 :(得分:0)
只需使用setTimeout()
function loadNewSubmenu() {
document.getElementById("content-1").className = "hide-part";
setTimeout(function() {
document.getElementById("content-2").className = "show-part";
}, 1000)
}
&#13;
.hide-part {
display: none;
}
&#13;
<button id="content-1" class="show-part">B1</button>
<button id="content-2" class="hide-part">B2</button>
<button id="content-1" onclick="loadNewSubmenu()">click me</button>
&#13;
答案 2 :(得分:0)
使用 setTimeout 代替睡眠
function loadNewSubmenu()
{
document.getElementById("content-1").className = "hide-part";
setTimeout(function(){ document.getElementById("content-2").className = "show-part"; },1000);
}
.hide-part{
display : none;
}
<button id="content-1" class="show-part">B1</button>
<button id="content-2" class="hide-part">B2</button>
<button id="content-3" onclick="loadNewSubmenu()">click me</button>