滚动粘滞标头,导致以下div到达顶部时跳转 [英] Scrolling sticky header causing following div to jump when it reaches the top

查看:64
本文介绍了滚动粘滞标头,导致以下div到达顶部时跳转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

滚动标题出现问题,它从浏览器底部开始,一旦页面向下滚动并且标题到达顶部,它就可以修复.

I have an issue with a scrolling header, it starts life at the bottom of the browser, once the page scrolls down and the header reaches the top, it fixes.

问题在于修复后,以下div会说将标题的高度跳到顶部.

The issue is when it fixes, the following div will say jump the height of the header to the top.

这是我的jQuery

Here's my jQuery

var elementPosition = $('header').offset();

$(window).scroll(function(){
    if($(window).scrollTop() > elementPosition.top){
        $('header').addClass("stick");
    } else {
        $('header').removeClass("stick");
    }
});

这是CSS

.stick {
    position:fixed;
    top:0;
}

推荐答案

之所以会出现此问题,是因为在固定标题时,您正在从页面流中删除它.这样一来,以下内容就会跳起来"取代它.

The problem occurs because when making the header fixed, you are removing it from the flow of the page. In doing so, the following content "jumps" up to take its place.

一种解决方案是添加一个"ghost" div,该div与标题的高度相同,并且默认情况下是隐藏的.

One solution is to add a "ghost" div which is the same height as the header, and hidden by default.

在标题到达窗口顶部并将其固定到位的位置上,您还取消隐藏了ghost div,它立即取代了它的位置,并防止了以下内容的跳转.

At the point the header reaches the top of the window and you fix it in place, you also unhide the ghost div, which immediately takes its place and prevents the following content from jumping up.

另一种解决方案是在以下内容中添加"margin-top",因为标题的高度是多少.这将具有相同的效果,并将防止其余页面内容跳跃.

Another solution is to add "margin-top" to the following content, for however tall your header is. This will have the same effect and will prevent the rest of the page content jumping.

这篇关于滚动粘滞标头,导致以下div到达顶部时跳转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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