我用 jQuery 创建了一个动画,它按顺序(反向)在文本行中滑动。它非常简单,悬停一次时效果很好。然而,当快速移动鼠标时,线条将以看似随机的顺序呈现动画。
请参阅下面的 GIF 进行演示。第一个悬停是动画的外观。悬停之后,我将鼠标移入移出,以演示文本行随机动画的问题。
请参阅下面的代码示例:
HTML
<div class="image-block">
<p>Text Line 1</p>
<p>Text Line 2</p>
<p>Text Line 3</p>
<p>Text Line 4</p>
<p>Text Line 5</p>
</div>
CSS
/* Hide text lines to begin with */
.image-block {
position: relative;
overflow: hidden;
background-image: url('background-image.png');
}
.image-block p {
position: absolute;
left: -120%
}
jQuery
jQuery(document).ready(function() {
// Animate text lines on hover with CSS 'left'.
jQuery('.image-block').hover(function() {
jQuery.fn.reverse = [].reverse;
time = 0;
speed = 300;
jQuery(this).find('p').reverse().each(function() {
jQuery(this).stop(true).delay(time).animate({
left: '0'
}, speed,
function() {
jQuery(this).stop(true).delay(time).animate({
left: '0'
}, speed);
})
time = time + 125;
speed = speed - 25;
});
}, function() {
// Animate text lines on hover release with CSS 'left'.
jQuery(this).find('p').reverse().each(function() {
jQuery(this).stop(true).animate({
left: '-120%'
}, 150)
});
});
});
当快速移动鼠标时,上面的两行怎么可能首先动画?释放悬停后是否需要以某种方式重置我的动画?我向动画添加了 stop(true)
但这并没有解决问题。
提前谢谢您。
最佳答案
这也让我摸不着头脑。正如我之前已经解决过的那样,但为了解释起见,必须详细说明。
问题在于您在动画中使用的 .delay()
方法。当你给动画添加延迟时,它是无法被清除的。因此,当您的hoverIn/hoverOut 速度非常快时,之前的悬停事件的处理程序不会被清除,并且一些 p
标签的动画效果会乱序。有关 .delay()
的详细说明,请在此处查看所选答案 StackOverflow或更好jQuery delay
关于您的问题的解决方案。您可以使用setTimeout
来替代delay
。我做了这个jsfiddle作为使用 setTimeout
解决问题的解决方法。
您可以使用setTimeout
这样做:
jQuery(document).ready(function() {
// Animate text lines on hover with CSS 'left'.
// To store setTimeout response
var animations = new Array(5);
jQuery('.image-block').hover(function() {
jQuery.fn.reverse = [].reverse;
time = 0;
speed = 300;
jQuery(this).find('p').reverse().each(function(index, item) {
// Clear previous handlers
clearTimeout(animations[index]);
// Set new handlers and add to `animations`
animations[index] = setTimeout(function(){
jQuery(item).stop(true).animate({
left: '0'
}, speed);
}, time);
time = time + 125;
speed = speed - 25;
});
}, function() {
// Animate text lines on hover release with CSS 'left'.
jQuery(this).find('p').each(function(index, item) {
// Clear previous handlers
clearTimeout(animations[index]);
jQuery(item).stop(true).animate({
left: '-120%'
}, 150);
});
});
});
为hover(MouseIn)添加动画时,需要将setTimeout
返回值保存到变量中,以便在MouseOut时清除这些值。如果您需要有关 fiddle 的更多解释,请回复。
更新: .clearQueue()
实际上并不需要,因此将其删除并更新了 fiddle 代码。
关于javascript - 快速悬停时 jQuery animate() 序列乱序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46689302/