如何让div固定后你滚动到那个div? [英] How to make div fixed after you scroll to that div?

查看:142
本文介绍了如何让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 the page and you need to scroll to get to that div.

如果我使用

.divname
{
position: fixed;
}

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

div will appear before it should appear normally. Maybe the 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.

推荐答案

我知道这只是标记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天全站免登陆