滚动到该 div 后如何使 div 固定? [英] How to make div fixed after you scroll to that div?

查看:20
本文介绍了滚动到该 div 后如何使 div 固定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使 div 在滚动到 div 后保持固定?我有一个位于页面后面的 div,您需要滚动才能找到该 div.

How to make a div remain fixed after you scroll to that div? I have a div that is later in a page and you need to scroll to get to that div.

如果我使用:

.divname {
  position: fixed;
}

div 会在正常出现之前出现.也许我需要的一个很好的例子是 9gag 上的第二个广告.如果您的屏幕分辨率足够低,加载首页后您将看不到该广告,但向下滚动后,您会看到第二个广告,并且在向下滚动时它会保持固定.

The div will appear before it should appear normally. Maybe a good example of what I need is second ad on 9gag. If your screen resolution is low enough, you won't see that ad after you load the front page, but after you scroll down, you'll see the second ad and it will remain fixed while you scroll down.

推荐答案

现在这仅适用于 CSS,请参阅 https://stackoverflow.com/a/53832799/1482443

This is now possible with CSS only, see https://stackoverflow.com/a/53832799/1482443

如果有人需要 jQuery 方法,以下是 8 年前发布的原始答案:

In case anyone needs jQuery approach, below is the original answer as it was posted 8 years ago:

我知道这仅被标记为 html/css,但您不能仅使用 css 来做到这一点.最简单的方法是使用一些 jQuery.

I know this is tagged html/css only, but you can't do that with css only. Easiest way will be using some jQuery.

var fixmeTop = $('.fixme').offset().top;       // get initial position of the element

$(window).scroll(function() {                  // assign scroll event listener

    var currentScroll = $(window).scrollTop(); // get current position

    if (currentScroll >= fixmeTop) {           // apply position: fixed if you
        $('.fixme').css({                      // scroll to that element or below it
            position: 'fixed',
            top: '0',
            left: '0'
        });
    } else {                                   // apply position: static
        $('.fixme').css({                      // if you scroll above it
            position: 'static'
        });
    }

});

http://jsfiddle.net/5n5MA/2/

这篇关于滚动到该 div 后如何使 div 固定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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