假设我有以下标题
<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'
});
}
});
答案 0 :(得分: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)})
})