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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:18:04  来源:igfitidea点击:

Fixing an element when it reaches the top of the page

javascriptjquerycss

提问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. .affixis 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:fixedstyle 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 affixto the sidebarwhen the user scrolls down and reaches the top of the sidebar. Now add the fixed position to the sidebarwith class name affix.

这将添加一个类名affixsidebar当用户向下滚动并到达侧边栏的顶部。现在将固定位置添加到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/(滚动查看它的实际效果,您可以对页面上的任何元素执行此操作)。如果这不是您要找的东西,请告诉我,我会帮您想出适合您需求的东西。