简体   繁体   English

将元素粘贴到页面顶部,直到出现该类型的下一个元素

[英]stick element to top of page until next element of that type appears

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>
<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. 我想将“第1章”绝对放置在页面顶部,或者将其放置在页面顶部,直到用户向下滚动到“第2章”开始的位置,此时“第2章”显示在页面顶部。

We can add wrapper classes and divs if needed. 如果需要,我们可以添加包装器类和div。 Solutions that use JQuery would be great. 使用JQuery的解决方案会很棒。

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. 您可以创建一个始终位于屏幕顶部的div而不是更改标题的位置,并在检测到用户滚动过去时将标题克隆到其中。 See a working demo: http://jsfiddle.net/8sANt/ 查看有效的演示: http : //jsfiddle.net/8sANt/

JS : 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: 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? 如果我理解正确,那么您想要类似于Google图片分页的内容吗? 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. 您想要做的是在用户滚动时检查H2元素的位置,如果它小于其父容器的滚动顶部,则使其文本成为绝对定位元素中的候选者在顶部。 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. 一旦您击中一个不在负数中的H2,就会跳出循环并将文本添加到绝对定位的元素中。

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

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