如何使div向下滚动到页面一旦到达页面顶部? [英] How to make div scroll down with a page once it reaches top of page?

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

问题描述

我知道标题有点混乱;但基本上我想做的是在这个网站上清楚地显示 http://9gag.com 向下滚动并注意侧边栏,一旦第二个广告到达页面顶部,有两个广告开始向下滚动一个页面。

I know title is a bit confusing ;D but basically what I want to do is clearly demonstrated on this website http://9gag.com scroll down and pay attention to sidebar, there are 2 advertisements once 2nd advertisement reaches top of the page it starts scrolling down with a page.

我想知道如何做这个? html / css或jQuery解决方案是预先的。

I would like to know how to do this? html/css or jQuery solutions are prefared.

推荐答案

Kevin指出,你需要做的是听文档 scroll 事件。当它被触发时,你需要查看 scrollTop 的值。

As Kevin points out, what you need to do is to listen to the document's scroll event. When that is fired, you'll want to look at the value of scrollTop.

$(document).scroll(function() {

    var useFixedSidebar = $(document).scrollTop() >= myThresholdValue;
    $('.my-sidebar-items').toggleClass('fixed', useFixedSidebar);

});

您的CSS基本上看起来像这样:

And your CSS would basically look like this:

.my-sidebar-items.fixedSidebar { position: fixed; }

一个复杂的因素是,你可能希望项目被固定在他们的新的,位置,你会想做这样的事情:

A complicating factor is that you'll probably want the items to be fixed in their new, top positions, and you would want to do something like this:

.my-sidebar-items.fixedSidebar { position: fixed; top: 0 }

但是,这可能会将您的项目堆叠在一起。解决方法是将 fixedSidebar 类放在容器上,并按照所述使用类。

However, that would probably stack your items on top of one another. A solution to that would be to put the fixedSidebar class on a container, and use the class as described.

演示

这篇关于如何使div向下滚动到页面一旦到达页面顶部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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