javascript 当元素到达页面顶部时修复元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23081656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fixing an element when it reaches the top of the page
提问by Sebastian
I currently have a script that fixes a <header>
element after a certain amount of scrolling. How would I modify it so that the element scrolls normally until it gets to the top of the page thenfixes. Something like this.
我目前有一个脚本,可以<header>
在一定量的滚动后修复一个元素。我将如何修改它以便元素正常滚动,直到它到达页面顶部然后修复。像这样的东西。
Current code:
当前代码:
$(document).ready(function(){
// Fix Sidebar
windowHeight = $(window).height();
sidebarHeight = $(".sidebar").height() + 70;
console.log(sidebarHeight + ", " + windowHeight);
if (windowHeight > sidebarHeight) {
$('.sidebar').addClass("affix");
}
});
N.B. .affix
is just {position:fixed}
.
NB.affix
只是{position:fixed}
。
Site
地点
The <header>
element is the sidebar on the right with the big green demo button.
该<header>
元素是右侧带有绿色大演示按钮的侧边栏。
回答by James
To make your sidebar fixed when the user scrolls down and reaches the top of the sidebar, use Jquery to add a class name to the sidebar when it reaches the window top position and add the position:fixed
style to this new class.
要在用户向下滚动并到达侧边栏顶部时固定侧边栏,请使用 Jquery 在到达窗口顶部位置时向侧边栏添加一个类名,并将position:fixed
样式添加到这个新类中。
var stickySidebar = $('.sidebar').offset().top;
$(window).scroll(function() {
if ($(window).scrollTop() > stickySidebar) {
$('.sidebar').addClass('affix');
}
else {
$('.sidebar').removeClass('affix');
}
});
This will add a class name affix
to the sidebar
when the user scrolls down and reaches the top of the sidebar. Now add the fixed position to the sidebar
with class name affix
.
这将添加一个类名affix
到sidebar
当用户向下滚动并到达侧边栏的顶部。现在将固定位置添加到sidebar
类名affix
。
.sidebar.affix{
position:fixed;
top:0;
right:0;
}
DEMO
演示
回答by Mathew MacLean
I believe you may be looking for something like this: http://stickyjs.com/(scroll to see it in action, you can do this to any element on a page). If that isn't what you are looking for let me know and I will help come up with something that suits your needs.
我相信您可能正在寻找这样的东西:http: //stickyjs.com/(滚动查看它的实际效果,您可以对页面上的任何元素执行此操作)。如果这不是您要找的东西,请告诉我,我会帮您想出适合您需求的东西。