Scrolltop()(不能反转动画)

Scrolltop() (can't reverse the animation)

本文关键字:动画 不能 Scrolltop      更新时间:2023-09-26

嘿,我正试图通过向左移动10%和向右移动10%来让这两个div相互离开。它们会在1000之后相互移出,但在我滚动回1000 之前之后不会再移动

$(document).ready(function(){
var jq  = $("#jqimg")
var kevin = $("#kevinimg")

 $(window).scroll(function () {
      if ($(this).scrollTop() > 1000) {
        kevin.animate({
            marginLeft: "10%",
        },600);
        jq.animate({
            marginRight:"10%",
        },600);
      } 
  });
});

我试着添加这个,但这只是打破了

   else {
        kevin.animate({
            marginLeft: "0%",
        },600);
        jq.animate({
            marginRight:"0%",
        },600);
      }

有人有解决方案吗?

这是因为之前的动画没有完成。使用queue: false可以防止动画链接。并使用marginLeft: null而不是0%从样式属性中删除margin属性示例

$(window).scroll(function() {
    if ($(this).scrollTop() > 1000) {
        $('div').animate({
            marginLeft: '10%'
        }, {
            queue: false
        });
    } else {
        $('div').animate({
            marginLeft: null
        }, {
            queue: false
        });
    }
});

另一种方式是使用.stop().finish()。但在这种情况下,您会在元素上丢失另一个动画过程。示例

$(window).scroll(function() {
    if ($(this).scrollTop() > 1000) {
        $('div').stop().animate({
            marginLeft: '10%'
        });
    } else {
        $('div').stop().animate({
            marginLeft: null
        });
    }
});