我想检查过渡何时结束,但它会触发两次/多次,我只想在单击元素并调用函数时检查一次,而在删除类时不再检查,我尝试使用 one()
、stopPropagation()
甚至在函数末尾 return false
但它不起作用,如何实现?
这是一个例子:
$(document).ready(function() {
$(document).on("click", ".main", function() {
$(this).addClass('example');
checkEndTransition()
})
function checkEndTransition() {
$(document).on("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", ".main", function() {
$.when($(this)).done(function() {
console.log("Finished")
var val = $(this)
setTimeout(function () {
val.removeClass("example")
}, 1500)
})
})
}
})
.main{
width: 170px;
height: 170px;
background-color: lightgrey;
transition: 1.5s;
}
.example{
width: 250px;
height: 250px;
background-color: #7fff7f;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main">
<div>
</div>
<div>
最佳答案
$(document).ready(function() {
$(document).on("click", ".main", function() {
$(this).addClass('example');
checkEndTransition();
})
function checkEndTransition() {
var flag = true;
$(document).on("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", ".main", function() {
if(flag){
$.when($(this)).done(function() {
console.log("Finished");
var val = $(this);
setTimeout(function () {
val.removeClass("example");
}, 1500)
})
}
flag = false;
})
}
})
.main{
width: 170px;
height: 170px;
background-color: lightgrey;
transition: 1.5s;
}
.example{
width: 250px;
height: 250px;
background-color: #7fff7f;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main">
<div>
</div>
<div>
你的问题是 $(document).on("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", ".main", function()
运行多次。你可以使用一个标志让它只运行一次时间。使用上面的脚本,它将起作用。
关于javascript - 如何防止此 transitionend 事件运行两次/多次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49688457/