gpt4 book ai didi

jquery - 使用 jQuery 通过滑动来制作动画

转载 作者:行者123 更新时间:2023-12-01 05:13:57 27 4
gpt4 key购买 nike

您好,我在左右滑动时移动幻灯片 div 时遇到问题。我正在使用:

$("#slidetrack").on("swipeleft",function(){
$("#slidetrack").animate({
"margin-left": "-=800px" //go left
}, {duration: 1600, easing: "easeOutExpo", queue: false});

$("#slidetrack").on("swiperight",function(){
$("#slidetrack").animate({
"margin-left": "+=800px" //go right
}, {duration: 1600, easing: "easeOutExpo", queue: false});

这工作正常,但是当用户再次滑动得太快时就会出现问题。假设用户快速连续滑动两次,第二次滑动仅发生在第一次滑动的 800px 动画中 400 像素处,面板轨道应移动的像素总数为 1600,但在这种情况下,它只会移动 400+ 800=1200像素。

我尝试使用 is(':animated') 来检查动画是否仍在发生,从而防止另一个动画:

        if ($("#slidetrack").is(':animated')) {

return false;

};

这在一定程度上确实有效,但并不合适,因为用户可能想要快速滑动幻灯片,但无法使用此方法做到这一点。

那么有没有更好的方法呢?

提前致谢

最佳答案

您可以这样做,以便连续的滑动将导致当前正在运行的动画立即 .stop()通过将 true 传递给两个可选参数:clearQueuejumpToEnd

$('#slidetrack').on('keydown', function (e) {
var $track = $(this);
var animating = $track.is(':animated');

if (animating) {
// Stops the currently-running animation,
// removes queued animation and
// completes the animation immediately
$track.stop(true, true);
}

var offset = 200;
var direction = {
[$.ui.keyCode.LEFT]: '-=',
[$.ui.keyCode.RIGHT]: '+=',
}
[e.which || e.keyCode];

if (direction) {
$('#slidetrack').animate({
'left': `${direction}${offset}px`
}, {
duration: 1600,
easing: "easeOutExpo",
queue: false,
step: function (n) {
$track.text(Math.floor(n) + 'px');
}
});
}
});
#slidetrack {
background-color: lavender;
width: 55px;
height: 45px;
text-align: center;
position: relative;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>

<p>Click on the box once, and use LEFT & RIGHT arrow (simulating swipes)</p>
<div id="slidetrack" tabindex="0"></div>

关于jquery - 使用 jQuery 通过滑动来制作动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54406329/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com