我通过添加事件类来触发过渡动画。
在动画结束时,我删除了事件类(在 延迟),以便再次触发。
这在第一次迭代时效果很好,但后续迭代和单击 close
函数不会重置延迟计数。
超时计时器显然需要在每次点击时清除或重置,但我无法让它始终如一地工作。我一直在尝试使用 clearTimeout()
函数。
$("#btn").on('click', function() {
$("#msg").prop("class", "alert active");
removeActive();
});
function removeActive() {
$("#msg").on("transitionend", function() {
setTimeout(function() {
$("#msg").removeClass("active");
}, 3000)
});
}
$("#close").on("click", function() {
$("#msg").removeClass("active");
});
.alert {
position: fixed;
right: 20px;
bottom: -100px;
display: flex;
padding: 10px;
width: auto;
max-width: calc(100% - 40px);
background: #3dc0f1;
color: #fff;
transition: all ease-in-out 0.3s;
z-index: 10;
}
.alert.active {
bottom: 20px;
}
#msg-tx {
padding: 10px 20px 10px 10px;
}
#close {
display: flex;
align-items: center;
padding: 10px;
border-radius: 5px;
transition: all ease-in-out 0.3s;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn" type="submit">Go</button>
<div id="msg" class="alert">
<p id="msg-tx">Hello There</p>
<div id="close">X</div>
</div>
多次单击 Go 按钮,导致超时变得不一致。
最佳答案
通过动画化另一个属性(在本例中为翻译)来依赖 CSS 延迟,并使 jQuery 代码更容易。
$("#btn").on('click', function() {
$("#msg").removeClass("active");
setTimeout(function() {
$("#msg").addClass("active");
}, 200)
});
$("#close").on("click", function() {
$("#msg").removeClass("active");
});
.alert {
position: fixed;
right: 20px;
bottom: -100px;
display: flex;
padding: 10px;
width: auto;
max-width: calc(100% - 40px);
background: #3dc0f1;
color: #fff;
transition: all ease-in-out 0.2s;
z-index: 10;
}
.alert.active {
bottom: 20px;
transform:translateY(calc(100% + 40px));
transition: bottom ease-in-out 0.3s,transform 0.3s 3s;
}
#msg-tx {
padding: 10px 20px 10px 10px;
}
#close {
display: flex;
align-items: center;
padding: 10px;
border-radius: 5px;
transition: all ease-in-out 0.3s;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn" type="submit">Go</button>
<div id="msg" class="alert">
<p id="msg-tx">Hello There</p>
<div id="close">X</div>
</div>
关于javascript - jQuery - 设置和重置转换延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57921083/