使用 jquery.animate() 和 jquery.scroll() 反转由动画效果引起的 CSS 更改

Reversing the changes on CSS caused by the animation effect using jquery.animate() and jquery.scroll()

本文关键字:jquery CSS 更改 animate scroll 使用 动画      更新时间:2023-09-26

有没有办法根据滚动的位置来反转jQuery.animate()引起的CSS更改?我正在开发一个网站,我希望当用户向下滚动时在元素上出现某种动画效果。之后,当用户向上滚动时,元素必须返回到其以前的状态。举个例子:

$(window).scroll(function(){
    if(this.scrollTop() >= 300){  //Scrolling down to a point 300 or more
        $('.foo').animate({
            'width': 100 
           'height': 100 
        }, 500, 'swing');     
     }
});

从上面的代码片段中可以看出,当用户向下滚动时,就会发生这种效果。现在下面是一个代码,我可以在逻辑上想到反向效果将如何工作:

if(this.scrollTop() <= 300) {  //Scrolling down to a point 300 or more    
    $('.foo').animate({
        'width': 10 
        'height': 10
    }, 500, 'swing');     
 }

单击"小提琴"以查看运行中的代码并获得更好的见解。

但是,我已经看到很多插件这样做,有没有更好的方法仅使用jQuery.scroll()绑定jQuery.animate()来完成上述场景?如果是这样,你能给我举个例子吗?或者你能把我引导到一个链接吗?请指导我/建议我。

感谢您的帮助!

您可以为此使用一个类,创建一个具有所需属性的类,在您的情况下

.scrolled {
  height: 100px;
  width: 100px;
}

然后addClass,它接受你想要的其他选项,所以你可以

if(this.scrollTop() >= 300){
    this.addClass('scrolled', 500, 'swing');
}
if(this.scrollTop() < 300){
    this.removeClass('scrolled', 500, 'swing);
}

如果你不需要强制jquery编辑对象的CSS,你可以告诉它添加/删除类,这将给你类似的效果。

如果你对象的样式已经组合成 10px 宽/高,那么你可以有一个像

.bar{
   height: 100px;
   width: 100px;
}

在你的JavaScript代码中:

if(this.scrollTop() >= 300){
    this.addClass('bar');
}

那你可以做

removeClass('bar'); 

当你不需要它时。

https://api.jquery.com/addclass/

https://api.jquery.com/removeclass/