简体   繁体   English

当用户向下滚动时,如何使侧边栏停在特定div?

[英]How can I make the sidebar stop at a specific div while the user scrolls down?

I'm using this code to make the sidebar fixed at a certain div while the user scrolls down. 当用户向下滚动时,我正在使用此代码使侧边栏固定在某个div上。 The problem is that I have to manually enter in a threshold number and this isn't always ideal since the position of the section may change or be inconsistent across various browsers and systems. 问题是我必须手动输入一个阈值数字,这并不总是理想的,因为该部分的位置可能会在各种浏览器和系统中发生变化或不一致。 I'm wondering if there is a way I can automatically have the sidebar become fixed once the user scrolls down and .Section2 hits the top. 我想知道是否有一种方法,一旦用户向下滚动,我可以自动让侧边栏固定.Section2击中顶部。

Fiddle 小提琴

http://jsfiddle.net/EvAdP/6/ http://jsfiddle.net/EvAdP/6/

HTML HTML

<header>
    I'm the header
</header>
<div id="container">
    <aside id="sidebar">
        <div class="section1">I'm a sidebar section</div>
        <div class="Section2">I'm another sidebar section</div>
    </aside>
    <section id="content">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis turpis turpis, dictum id sollicitudin eu, molestie ut tellus. Nam tincidunt mauris in erat vehicula adipiscing. Morbi cursus orci a nisl auctor nec porta eros consectetur. Vestibulum auctor congue mi, vitae molestie nisi faucibus vel. Ut et dui ut mauris posuere dignissim in et sapien. Duis a nulla ipsum. Duis accumsan porttitor justo at pretium. Aliquam quam urna, eleifend vitae consequat et, pharetra eu lectus. Etiam id magna mi. Donec pulvinar nibh in felis placerat condimentum consectetur enim iaculis. Integer et sapien justo, ac ullamcorper nisi. Praesent sed mauris non lacus pellentesque condimentum. Sed hendrerit consectetur nisi bibendum convallis. Pellentesque semper faucibus tortor malesuada dignissim.</p>
        <p>Aliquam adipiscing commodo est, eu venenatis mi ullamcorper cursus. Integer vel magna in neque aliquet hendrerit. Mauris eros nisl, venenatis quis ultricies id, faucibus et mi. Nunc sit amet nulla odio. Phasellus quis eros id tortor imperdiet faucibus ac eu metus. Curabitur at feugiat dui. Vivamus imperdiet lectus id orci sodales sit amet eleifend ante tempus. Mauris vehicula elit eu dolor volutpat porttitor.</p>
        <p>Praesent pretium convallis diam, sed faucibus dolor convallis eget. Pellentesque sollicitudin erat ac ligula viverra vel mollis diam tristique. Nulla tempus ligula ac dui fringilla consequat. Suspendisse accumsan volutpat semper. Morbi bibendum vehicula nibh id condimentum. Maecenas auctor mattis libero, ut suscipit tellus interdum quis. Nam eu dolor orci. Proin et tortor diam. Phasellus blandit leo ut elit faucibus varius. Donec condimentum congue lectus, sit amet gravida diam aliquet at.</p>
        <p>Praesent eu libero sem. Phasellus elementum posuere velit, id aliquet ante elementum non. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus faucibus rutrum luctus. Suspendisse nec facilisis neque. Cras dui lacus, pellentesque at fermentum sollicitudin, aliquam et nisi. Proin eget sem diam, nec faucibus nulla. In nibh dolor, interdum at egestas a, dictum sed massa. Integer quis elit vitae enim lacinia tristique ac id purus. Pellentesque fermentum tempor sem sit amet venenatis. Nulla facilisi. Donec semper ultrices magna, posuere mattis turpis rhoncus ut.</p>
        <p>Etiam porttitor erat sit amet odio egestas sit amet mollis magna convallis. Sed porttitor aliquet velit at placerat. Proin in turpis non velit gravida eleifend quis ac magna. Nunc sagittis, eros a pulvinar gravida, mauris urna viverra lorem, non posuere orci ligula vitae justo. Nulla neque erat, tempus at dapibus sit amet, scelerisque ac sapien. In in magna sapien, at auctor tellus. Donec nec turpis ligula, vitae scelerisque arcu.</p>
    </section>
</div>

CSS CSS

body {
    margin:0;
}

header {
    line-height:100px;
    height:100px;
    background-color:#F00;
}

#container {
    position:relative;
}

#sidebar {
    position:absolute;
    background-color:#0F0;
}

#sidebar .section1 {
    background: blue;
    height: 150px;
    width: 80px;
}

.Section2.fixed {
   position:fixed;
   top:0;
}
#sidebar .Section2 {
    background: pink;
    height: 150px;
    width: 80px;
}
#sidebar.fixed {
    position:fixed;
    top:0;
}

#content {
    margin-left:100px;
}

p:first-child {
    margin-top:0;
}

JS JS

$(window).scroll(function () {
    var threshold = 250;
    if ($(window).scrollTop() >= threshold)
        $('.Section2').addClass('fixed');
    else
        $('.Section2').removeClass('fixed');
});

Instead of specifying the threshold value try this 试试这个,而不是指定阈值

var threshold =  $('.Section2').offset().top;
$(window).scroll(function () {
    if ($(window).scrollTop() >= threshold)
        $('.Section2').addClass('fixed');
    else
        $('.Section2').removeClass('fixed');
});

DEMO DEMO

Further to our discussions I thought I would post an alternative to the accepted solution that will work with flexible content. 在我们的讨论之后,我想我会发布一个可以使用灵活内容的公认解决方案的替代方案。

It simply gets Section2 offset each time the scroll event is fired (but only if its not already .fixed ): 每次触发滚动事件时它只会获得 Section2偏移量(但仅当它尚未 .fixed ):

EDIT : simply check that threshold is greater than zero: 编辑 :只需检查阈值是否大于零:

var $Section2 = $('.Section2');
$(window).scroll(function () {
    var threshold =  $Section2.offset().top;
    if (threshold>0 && $(window).scrollTop() >= threshold){
        $Section2.addClass('fixed');
    } else {
        $Section2.removeClass('fixed');
    }
});

DEMO DEMO

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

相关问题 当用户向下滚动时,如何检测到用户在视口的中间? - How can i detect that the user is in the middle of the viewport while user scrolls down? 当用户向下滚动时,如何使另一个 HTML 页面出现在 HTML 页面中? - How can I make another HTML page appear within an HTML page when the User Scrolls down? 如何使 header 仅在大屏幕上具有粘性,但在用户向下滚动时在移动设备上消失? - How can I make the header be sticky only on large screens but disappears on mobile as the user scrolls down? 如何使侧边栏停在某个div上? - How do I make the sidebar stop at a certain div? 如何在用户向下滚动时更改图像? - How can I change an image when the user scrolls down? 当用户向下滚动时显示Div - Reveal Div as user scrolls down 当用户单击链接时,如何使div从顶部向下滚动? - How to make a div that scrolls down from top when user clicks link? 我怎样才能让我的Intersection Observer仅将div放在屏幕上一次,而当用户滚动离开时不将其删除? - How can I make me Intersection Observer only put the div on the screen once and not remove it when the user scrolls away? 无论访问者滚动的页面有多低,如何使DIV停留在屏幕顶部? - How do I make a DIV stay at the top of the screen no matter ow far down the page my visitor scrolls? 使侧边栏在某个div处停止 - Make sidebar stop at a certain div
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM