2015-06-20 107 views
2

假设我有标题词就像下面多个固定标题

<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.How我可以做到这一点?

下面我已经试过..

$(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/

+0

尝试使用'.each()'来定位每个元素的'.fixontop'类。 –

+0

[Freeze Header until Irrelevant(HTML,CSS and JS)]可能的重复](http://stackoverflow.com/questions/7385068/freeze-header-until-irrelevant-html-css-and-js) – jcuenod

回答

0

检查这一个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)}) 
})