我目前有一个div在touchstart时向左移动-这工作得很好,但如果用户按下并释放多次,动画每次重置为3秒-这意味着它会逐渐变慢。如有任何建议或帮助,我将不胜感激。
$(".buttonLeft").on('touchstart', function(e){
e.preventDefault();
var myDiv = $(".cart01");
myDiv.clearQueue();
myDiv.stop();
$(".cart01").stop().animate({"left": "340px"}, 3000, easing, function() {
console.log("Cart01 left complete");
});
});
您可以将myDiv.is(':animated')
与您现有的代码组合。
var myDiv = $(".cart01");
if (!myDiv.is(':animated')) {
myDiv.animate({
"left": "234px"
}, 3000, "linear", function() {
console.log("Cart01 left complete");
});
}
注意,在演示中,我将touchstart
更改为click
$(".buttonLeft").on('click', function(e) {
e.preventDefault();
var myDiv = $(".cart01");
if (!myDiv.is(':animated')) {
myDiv.animate({
"left": "234px"
}, 3000, "linear", function() {
console.log("Cart01 left complete");
});
}
});
.t {
position: relative;
height: 200px;
width: 300px;
}
.cart01 {
position: absolute;
left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button class="buttonLeft">buttonLeft</button>
<div class="t">
<div class="cart01">cart01</div>
</div>
- 只使用
touch
一次。你可以用.one
代替.on
$(".buttonLeft").one('click', function(e) {
e.preventDefault();
var $this = $(this);
var Cart = $(".cart01");
Cart.animate({
"left": "100px"
}, 3000, "linear", function() {
console.log("Animation completed ");
});
});
.cart01 {
position: fixed;
padding : 10px;
top : 50px;
left : 0;
background : red;
color : #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="cart01">cart01</div>
<button class="buttonLeft">buttonLeft</button>
- 要确保动画在下一个
click/touch
之前完成-使用add/removeClass
和:not
选择器,您将需要event-binding-on-dynamic -created-line-items-with-parameter,因为在这种情况下类将动态添加
var num = 0;
$(document).on('click', ".buttonLeft:not(.animating)", function(e) { // use :not selector to prevent the click from the `animating` class
e.preventDefault();
var $this = $(this);
$this.addClass('animating'); // add the animating class
var Cart = $(".cart01");
Cart.animate({
"left": num == 0 ? "100px" : "0px"
}, 3000, "linear", function() {
console.log("Animation completed ");
num = num == 0 ? 1 : 0;
$this.removeClass('animating'); // remove the animating class
});
});
.cart01 {
position: fixed;
padding : 10px;
top : 50px;
left : 0;
background : red;
color : #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="cart01">cart01</div>
<button class="buttonLeft">buttonLeft</button>