jQuery animate() 在滚动暂停后触发

标签 jquery animation jquery-animate

我正在尝试制作一个简单的粘性导航栏,该导航栏在页面顶部不可见,并在向下滚动页面时向下滑动。首先,我使用了scrollUp()/ScrollDown(),但我不喜欢它的外观,因为它对高度进行动画处理,而我想对位置进行动画处理。只是看起来不一样而已。 所以我决定使用 animate() 并将其应用于 margin-top。

HTML:

<div>
...lots of blocks and text
</div>
<div class="top_bar">some elements here</div>

CSS:

.top_bar {
    margin-top: -70px; 
    height:70px; 
    position: fixed; 
    width: 100%; 
    left: 0; 
    top: 0; 
    z-index: 1000; 
    background:#156373; 
    color: #fff; 
    text-align:center;
}

JS:

var stickyBar = function(){
    var scroll = $(window).scrollTop();
    if (scroll > 100) {
        $('.top_bar').animate({
            "margin-top": 0
        },"fast");
        } else {
        $('.top_bar').animate({
            "margin-top": -70
        },"fast");
    }
};
$(window).scroll(function() {  
    stickyBar();  
});

问题是它在暂停一段时间后会产生动画。我将页面滚动到最顶部,等待一秒钟,然后顶部栏以动画方式关闭。我向下滚动页面,等待一秒钟,然后 top_bar 开始动画显示。

我不明白这个停顿是从哪里来的...... 请告诉我我做错了什么?

http://jsfiddle.net/hc31qds5/1/

最佳答案

您可能希望使用 CSS3 过渡来获得最灵敏的效果。试试这个:

CSS

.top_bar {
    max-height: 0;
    position: fixed;
    width: 100%;
    left: 0;
    top: 0;
    z-index: 1000;
    background:#156373;
    color: #fff;
    text-align:center;
    transition: all 0.4s cubic-bezier(0, 1, 0.5, 1);
}
.top_bar.sticky {
    max-height: 70px;
    height: 70px;
}

JS

$(window).scroll(function () {
    if ($(this).scrollTop() > 100) {
        $('.top_bar').addClass("sticky");
    } else {
        $('.top_bar').removeClass("sticky");
    }
});

FIDDLE

更新

这里是 jquery animate,没有延迟:

$(window).scroll(function () {
    if ($(this).scrollTop() > 100) {
        $('.top_bar').stop().animate({
            "margin-top": 0
        }, 200);
    } else {
        $('.top_bar').stop().animate({
            "margin-top": -70
        }, 200);
    }
});

FIDDLE

您只需要确保stop()之前的动画即可。

关于jQuery animate() 在滚动暂停后触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26833402/

相关文章:

iOS 缩小动画

ios - 动画:使用 Autolayout、Frame.Origin 和 Broken Constraints,还是第三种选择?

jquery动画完成

jquery - CSS3 TranslateX 相对于当前位置,如 jQuery animate

jquery - 无法将 zclip 对象应用于 onLoad() 之后创建的元素 id?

javascript - jquery 有没有办法避免扩展单元格扩展它所持有的父单元格

javascript - jQuery ui.selectmenu 未填充

javascript - 暂时删除事件监听器,然后在执行某些操作后立即将其添加回来

javascript - 如何为 div 背景的不透明度设置动画?

android - fragment 标准过渡没有动画