使用jQuery动画滚动 [英] Animate on scroll with jQuery

查看:96
本文介绍了使用jQuery动画滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我在使用滚动事件的条件尝试动画DOM的几个元素时遇到了问题。
首先,我使用的是Drupal 7,因此我使用的jQuery库是版本1.4.4。

Ok, I'm facing an issue when trying to animate several elements of the DOM, using a condition on a scroll event. First of all, I'm using Drupal 7 so the jQuery library I'm using is of version 1.4.4.

现在,我想收缩当页面向下滚动时,通过更改其中元素的css属性来缩小页眉的大小。

Now, I want to shrink the size of my header when the page srolls down by changing css properties of elements inside of it.

首先,在滚动事件中,我检查了scrollTop的位置。窗口。如果位置不同于0(意味着页面向下滚动),我会在标题内的元素上触发动画。

So first, on the scroll event, I check the scrollTop position of the window. If the position is different than 0 (meaning that the page is scrolled down), I trigger the animation on the elements inside the header.

如果位置等于零,我希望css属性回退到原始状态,以便标题检索其完整大小。

If the position is equal to zero, I want the css properties to fall back to their original state so the header retrieve its full size.

动画的第一部分工作正常。当我向下滚动页面时,标题会按预期收缩。但是当我将页面向上滚动到顶部时,第二个动画不起作用..动画都是错误的并且在几秒钟之后发生并且变得狂野,来回改变受 animate() function。

The first part of the animation works fine. When I scroll down the page, the header shrinks as expected. But when I scroll the page back up to the top, the second animation doesn't work.. the animations are all buggy and occur after several second and go wild, changing back and forth the css properties affected by the animate() function.

有没有人知道如何解决这个问题?

Does anyone have a clue on how to clear this out ??

以下是我正在使用的代码的简化部分:

Here is the simplified portion of the code I'm using:

$(window).scroll(function(){            

    if($(window).scrollTop() != 0){
        $('#myFirstElement').animate({marginTop: '20px'}, 300);
        $('#mySecondElement').animate({top: '20px'}, 300);
    }       
    else {
        $('#myFirstElement').animate({marginTop: '32px'}, 300);
        $('#mySecondElement').animate({top: '32px'}, 300);
    }

});


推荐答案

你可以使用像

http://jsfiddle.net/HjFH4/

$elem1 = $('#myFirstElement');
$elem2 = $('#mySecondElement');
var scrollState = 'top';

$(window).scroll(function(){ 

    var scrollPos = $(window).scrollTop();

    if( ( scrollPos != 0 ) && ( scrollState === 'top' ) ) {
        $elem1.stop().animate({marginTop: '0px'}, 300);
        $elem2.stop().animate({height: '10px'}, 300);
        scrollState = 'scrolled';
    }       
    else if( ( scrollPos === 0 ) && ( scrollState === 'scrolled' ) ) {
        $elem1.stop().animate({marginTop: '32px'}, 300);
        $elem2.stop().animate({height: '80px'}, 300);
        scrollState = 'top';
    }

});

这篇关于使用jQuery动画滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆