jQuery中动画粘滞导航的问题 [英] Issue with an animated, sticky navigation in jQuery

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

问题描述

我正在尝试创建一个动画的粘性导航,当用户滚动到某个点时,该导航将移动到文档的顶部.它几乎可以正常工作(并且在第一页加载时效果很好),但是当用户滚动到顶部然后又向下滚动第二次时,导航会跳动而不显示动画.谁能看到我做错了什么?

I'm trying to create an animated sticky navigation, that moves to the top of the document when the user has scrolled past a certain point. It's almost working (and does so fine on the first page load), but when the user scrolls to the top and then scrolls down for a second time, the navigation jumps without the animation. Can anyone see what I've done wrong?

到目前为止,这是我的jQuery:

Here's my jQuery so far:

var x = true;
$(window).scroll(function(){
    if( $(document).scrollTop() > 150 ){
        x = false;
        $(".header").addClass("pinned");
    }else if( $(document).scrollTop() === 0 ){
        $(".header").removeClass("pinned");
        x = true;
    }
    if(x === false){
        $(".pinned").animate({marginTop:"0px"}, 200);
    }
});

这是一个jsfiddle来演示我的问题以及我要实现的目标: http://jsfiddle. net/DzTRb/4/

And here's a jsfiddle to demonstrate my problem and what I'm trying to achieve: http://jsfiddle.net/DzTRb/4/

推荐答案

当jquery进行动画处理时,它会在完成后设置margin-top:0;,因此第二次将您的css类.pinnedmargin-top:-100px;一起无效.

When jquery is doing the animation, it sets margin-top:0; after complete, so second time your css class .pinned with margin-top:-100px; has no effect...

您必须做几件事:

  • 在动画完成后删除添加到.pinned元素的所有样式
  • 仅运行一个动画(检查是否已添加.pinned类)
  • 滚动到顶部时停止动画,以便jquery不再添加任何样式
  • remove any styles added to the .pinned element after the animation completes
  • run only one animation (check if the .pinned class is already added)
  • stop the animation when scrolled to top so jquery does not add any more styles

小提琴

这篇关于jQuery中动画粘滞导航的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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