以下代码段将使用jquery,css和javascript在页面加载时加载元素。
$('.callqueue').click(function(){
$('#dddnav').toggleClass('menu-open');
$('body').toggleClass('menu-open');
});
$(window).load(function (){
$('#dddnav').toggleClass('menu-open');
});
#man {
display:none;
}
#dddnav {
height:30%;
background:#333;
position:fixed;
top:0;
right:-270px;
width:300px;
transition:right .5s;
-webkit-transition:right .5s;
}
#dddnav.menu-open {
right:0;
transition:right .5s;
-webkit-transition:right .5s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button class="callqueue"> CLICK </button>
<div id="dddnav" style="background: red; top: 10%;">
<img id="man" src="http://placehold.it/200" />
</div>
但是,我希望元素在页面加载后3秒后加载,并在5秒后卸载而无需单击按钮。如何使用JavaScript完成此操作?我找到了此链接:https://css-tricks.com/forums/topic/toggle-classes-with-delays/,但我似乎无法使其正常工作。
请感谢您的任何回应,例如。谢谢!
答案 0 :(得分:1)
async
和await
为避免争用情况并确保每次对函数的调用都按正确的顺序进行(尽管对于toggleClass()
之类的方法来说顺序并不重要),请在{strong> {{ 3}} 。
$(window).load(openClose);
$('.callqueue').click(slideNav);
async function openClose() {
await new Promise((resolve, reject) => setTimeout(resolve, 3000));
var open = await slideNav();
await new Promise((resolve, reject) => setTimeout(resolve, 2000));
var close = await slideNav();
};
function slideNav() {
$('#dddnav').toggleClass('menu-open');
}
#man {
display: none;
}
#dddnav {
height: 30%;
background: #333;
position: fixed;
top: 0;
right: -270px;
width: 300px;
transition: right .5s;
-webkit-transition: right .5s;
}
#dddnav.menu-open {
right: 0;
transition: right .5s;
-webkit-transition: right .5s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button class="callqueue"> CLICK </button>
<div id="dddnav" style="background: red; top: 10%;">
<img id="man" src="https://placehold.it/200" />
</div>
答案 1 :(得分:0)
尝试一下:
$(window).load(function (){
var start_time = new Date().getTime();
while (true) {
if(new Date().getTime() - startTime > 3000){
$('#dddnav').toggleClass('menu-open');
break;
}
}
});
答案 2 :(得分:0)
怎么办
$('.callqueue').click(function(){
$('#dddnav').toggleClass('menu-open');
$('body').toggleClass('menu-open');
});
// Let's define a callable to be used inside setTimeout.
toggleIt = function(){
$('#dddnav').toggleClass('menu-open')
};
$(window).load(function(){
setTimeout(
function(){
toggleIt()
setTimeout(toggleIt, 2000) // 5s as 3 + 2
}, 3000
)
})
#man {
display:none;
}
#dddnav {
height:30%;
background:#333;
position:fixed;
top:0;
right:-270px;
width:300px;
transition:right .5s;
-webkit-transition:right .5s;
}
#dddnav.menu-open {
right:0;
transition:right .5s;
-webkit-transition:right .5s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button class="callqueue"> CLICK </button>
<div id="dddnav" style="background: red; top: 10%;">
<img id="man" src="http://placehold.it/200" />
</div>