实际上,我的问题是,我想在fadein
事件中div
click
,并在一段时间后自动fadeout
div
。
我做了一些事情,但是fadeout
函数无法正常工作。这是我的代码段:
.alert-box {
position: absolute;
left: 0;
right: 0;
bottom: 0;
width: 100%;
display: none;
padding: 20px 0;
background-color: red;
color: #fff;
}
.close {
position: absolute;
right: 10px;
top: 10px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>click me</button>
<div class="alert-box">
<span class="close">×</span>
<div class="content">
sample content
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('button').click(function() {
$('.alert-box').fadeIn('fast');
});
if ($('.alert-box').css('display') == 'block') {
$('.alert-box').delay(1000).fadeOut('fast');
}
});
</script>
答案 0 :(得分:3)
使用setTimeout
进行1秒后的淡入淡出
setTimeout (() => {
$('.alert-box').fadeOut('fast');
}, 1000)
也删除了不必要的代码。
.alert-box {
position: absolute;
left: 0;
right: 0;
bottom: 0;
width: 100%;
display: none;
padding: 20px 0;
background-color: red;
color: #fff;
}
.close {
position: absolute;
right: 10px;
top: 10px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>click me</button>
<div class="alert-box">
<span class="close">×</span>
<div class="content">
sample content
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('button').click(function() {
$('.alert-box').fadeIn('fast');
setTimeout(() => {
if ($('.alert-box').css('display') == 'block') {
$('.alert-box').delay(1000).fadeOut('fast');
}
}, 1000);
});
});
</script>
答案 1 :(得分:2)
您可以在fadeOut()
之后立即使用fadeIn()
,以提高延迟速度。
$(document).ready(function() {
$('button').click(function() {
$('.alert-box').fadeIn('fast').delay(1000).fadeOut('fast');
});
});
.alert-box{
position: absolute;
left: 0;
right: 0;
bottom: 0;
width: 100%;
display: none;
padding: 20px 0;
background-color: red;
color: #fff;
}
.close{
position: absolute;
right: 10px;
top: 10px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>click me</button>
<div class="alert-box">
<span class="close">×</span>
<div class="content">
sample content
</div>
</div>