开发者

stick element to top of page until next element of that type appears

开发者 https://www.devze.com 2023-02-05 12:33 出处:网络
I\'m having a hard time giving a good description of this, but bear with me: If I have a page structed like this

I'm having a hard time giving a good description of this, but bear with me:

If I have a page structed like this

<h2>Chapter 1</h2>
<p>Lots of text that has mutiple screen worths of content</p>
<h2>Chapter 2</h2>开发者_JAVA百科;
<p>Lots of text...</p>

I'd like to have "Chapter 1" absolutely positioned or whatever at the top of the page until the user scrolls down to where "Chapter 2" starts, at which point now "Chapter 2" is displayed at the top of the page.

We can add wrapper classes and divs if needed. Solutions that use JQuery would be great.


Rather than changing the positioning of your Headings, you can create a div that is always at the top of the screen and clone your headings into it as you detect that the user has scrolled past. See a working demo: http://jsfiddle.net/8sANt/

JS:

$(document).scroll(function () {
    var sticky = $('#sticky'), h2 = $('h2:first');

    if (!sticky.length)
        sticky = $('<div id="sticky">').appendTo('body');

    $('h2').each(function () {
        if ($(this).parents('#sticky').length) return; // Ignore cloned headings
        if ($(this).offset().top > $(window).scrollTop())
            return false; // Exit loop
        h2 = $(this);
    });

    sticky.empty().append(h2.clone());
});

CSS:

#sticky {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    background: white;
}


If I understand correctly you want something similar to Google's Image paging right? Where it displays the current page you're on at the top until the next page scrolls past and then becomes the new page.

What you want to do is when the user is scrolling, check to see the position of the H2 elements, if it is less than the scrolltop of it's parent container, make its text the candidate for being the one that is in the absolutely positioned element at the top. Once you hit a H2 that isn't in the negative break out of the loop and add the text to the absolutely positioned element.

0

精彩评论

暂无评论...
验证码 换一张
取 消