如何添加css到div一旦它到达页面的顶部(滚动时)? [英] How to add css to a div once it hits the top of the page (when scrolling)?
问题描述
我想这样做,当用户向下滚动到某个div,说#float,将div设置为margin-top:50px和位置固定,如果用户向上滚动撤消这些更改。很难理解我知道)))如果您转到此页面,并注意侧边栏一旦上下滚动您会看到我的意思。
I would like to make it so when user scrolls down and reaches a certain div, say #float, set that div to margin-top: 50px and position fixed, and if user scrolls back up undo those changes. It's hard to understand I know ))) If you go to this page and pay your attention to sidebar once scrolling up and down you will see what I mean.
当您向下滚动时,第二个广告也会随着页面滚动。
As you scroll down 2nd advertisement scrolls with a page too.
/ CSS?
推荐答案
这是一种在jQuery中执行的方法。
This is a way of doing it in jQuery.
此代码仅供参考;几乎可以肯定有一些定期维护的jQuery插件,可以为你做这件事 - 检查 GitHub 或 DailyJS 。
$(window).scroll(function() {
var styledDiv = $('#styledDiv'),
targetScroll = $('#float').position().top,
currentScroll = $('html').scrollTop() || $('body').scrollTop();
styledDiv.toggleClass('fixedPos', currentScroll >= targetScroll);
});
Here is a simple JSFiddle of the above in action.
编辑:现在已将此代码重构为更多优雅的解决方案。
Edit: Have now refactored this code to a more elegant solution.
编辑2 :收到有关问题的电子邮件后,我更新了上述代码, Firefox。因为 $('body')。scrollTop()
在Firefox中无效(请参阅 jQuery API page ),我们需要检查 html
和正文
元素。
Edit 2: Following an email I received about a question, I've updated the code above so that it also works in Firefox. As $('body').scrollTop()
will not work in Firefox (See comments on the jQuery API page), we need to check both the html
and body
elements.
这篇关于如何添加css到div一旦它到达页面的顶部(滚动时)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!