简体   繁体   English

当元素到达页面顶部时修复元素

[英]Fixing an element when it reaches the top of the page

I currently have a script that fixes a <header> element after a certain amount of scrolling.我目前有一个脚本,可以在一定量的滚动后修复<header>元素。 How would I modify it so that the element scrolls normally until it gets to the top of the page then fixes.我将如何修改它以便元素正常滚动,直到它到达页面顶部然后修复。 Something like this .这样的东西。

Current code:当前代码:

$(document).ready(function(){
    // Fix Sidebar 
    windowHeight = $(window).height();
    sidebarHeight = $(".sidebar").height() + 70;
    console.log(sidebarHeight + ", " + windowHeight);
    if (windowHeight > sidebarHeight) {
        $('.sidebar').addClass("affix");
    }
});

NB .affix is just {position:fixed} .注意.affix只是{position:fixed}

Site地点

The <header> element is the sidebar on the right with the big green demo button. <header>元素是右侧的侧边栏,带有大的绿色演示按钮。

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.当用户向下滚动并到达侧边栏的顶部时,这将向sidebar添加一个类名称affix Now add the fixed position to the sidebar with class name affix .现在将固定位置添加到sidebar并带有类名affix

.sidebar.affix{
    position:fixed;
    top:0;
    right:0;
}

DEMO演示

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).我相信您可能正在寻找这样的东西: http : //stickyjs.com/ (滚动查看它的实际效果,您可以对页面上的任何元素执行此操作)。 If that isn't what you are looking for let me know and I will help come up with something that suits your needs.如果这不是您要找的东西,请告诉我,我会帮助您想出适合您需求的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM