这是笔...
http://codepen.io/jareko999/pen/bZXbWP
jQuery 的“if”部分起作用,并在等于或低于 0 时将 .fixed 类添加到#header,但当 headerTop 高于 0(即“else”)时,它不会将其删除。我不明白这是怎么回事。 JS 新手,我想了解如何让它工作。谢谢。
HTML
<div class="content">
<div id="header"></div>
</div>
CSS
body {
overflow-x: hidden;
margin: 0;
}
#header {
width: 100%;
height: 80px;
background: blue;
z-index: 1;
}
.content {
position: absolute;
top: calc(100% - 80px);
width: 100%;
height: 200vh;
background: linear-gradient(to bottom, red, yellow);
}
.fixed {
position: fixed;
top: 0;
width: 100%;
background: blue;
}
jQuery
$(window).scroll(function() {
var top = $('#header').offset().top;
var headerTop = (top - $(window).scrollTop());
if (headerTop <= 0) {
$('#header').addClass('fixed');
} else {
$('#header').removeClass('fixed');
}
});
最佳答案
我需要获取父 div offset().top 而不是实际的 header 本身。这是基于父元素顶部位置的粘性标题的最终滚动函数。
http://codepen.io/jareko999/pen/bZXbWP
$(window).scroll(function() {
var top = $('.content').offset().top;
var headerTop = (top - $(window).scrollTop());
$('#header').toggleClass('fixed', headerTop <= 0);
console.log(headerTop);
});
关于javascript - 修复了滚动上的标题位置 - 如果其他不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39210075/