【问题标题】:Multiple Fixed headings on scroll滚动上的多个固定标题
【发布时间】:2015-06-20 19:29:48
【问题描述】:

假设我有如下标题

<h1 class="fixontop">heading 1</h1>
content goes here.
.
.
.
long paragraph.
<h1 class="fixontop">heading 2</h1>
2nd content goes here.
.
.
.
long paragraph.
<h1 class="fixontop">heading 3</h1>
3nd content goes here.
.
.
.
long paragraph.

所以当我滚动时,标题 1 应该固定在顶部,我向下滚动时,标题 2 应该固定,所有其他标题固定位置必须删除。我认为只能通过 jquery 实现。我该怎么做?

我在下面尝试过..

 $(window).scroll(function() {
    if ($(this).scrollTop() ) { //Here some condition which finds if the heading tag is in screenview.  
        $('.fixontop').css({
            'display': 'fixed'
        });
    }
});

这是小提琴http://jsfiddle.net/0can8pt9/

【问题讨论】:

标签: javascript jquery css


【解决方案1】:

看看这个https://jsfiddle.net/ctjdpe91/1/ 我认为为此目的使用类似航点的插件是个好主意

var scrollTimeout;
var breakpoints = [];

function fix_heading(heading){
    if( heading.hasClass('heading-fixed'))
        return 

    heading
        .addClass('heading-fixed')
         // prevent content jumping
        .parents('section').css('padding-top', heading.height())
}

function unfix_heading(heading){
    if(! heading.hasClass('heading-fixed'))
        return

    heading
        .removeClass('heading-fixed')
        .parents('section').css('padding-top', 0);    
}

function fix_headings(breakpoints){
    clearTimeout(scrollTimeout);
    scrollTimeout = setTimeout(function(){
        $(breakpoints).each(function(){
            var breakpoint = this;
            var breakpoint_heading = $('.fixontop[data-fix-on='+breakpoint+']')

            if(document.body.scrollTop > breakpoint ){
                fix_heading(breakpoint_heading)
            }

            if(document.body.scrollTop < ( breakpoint )){
                unfix_heading(breakpoint_heading)
            }

            //scrolled out of parent container
            if(document.body.scrollTop > (breakpoint + breakpoint_heading.parents('section').outerHeight())){
                unfix_heading(breakpoint_heading)   
            }

         })
     }, 30) //timeout here for better performance
}

$(function(){
    //setup breakpoints
    $('.fixontop').each(function(){
        breakpoints.push ($(this).position().top)
        $(this).attr('data-fix-on', $(this).position().top)
    })
    $(document).scroll(function(){fix_headings(breakpoints)})
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-27
    • 2017-07-23
    • 1970-01-01
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多