You could use simply css, positioning your element as fixed :(您可以简单地使用css,将元素定位为fixed :)
.fixedElement {
background-color: #c0c0c0;
position:fixed;
top:0;
width:100%;
z-index:100;
}
Edit: You should have the element with position absolute, once the scroll offset has reached the element, it should be changed to fixed, and the top position should be set to zero.(编辑:您应该将元素的位置设为绝对,一旦滚动偏移量到达该元素,则应将其更改为fixed,并将顶部位置设置为零。)
You can detect the top scroll offset of the document with the scrollTop function:(您可以使用scrollTop函数检测文档的顶部滚动偏移量:)
$(window).scroll(function(e){
var $el = $('.fixedElement');
var isPositionFixed = ($el.css('position') == 'fixed');
if ($(this).scrollTop() > 200 && !isPositionFixed){
$el.css({'position': 'fixed', 'top': '0px'});
}
if ($(this).scrollTop() < 200 && isPositionFixed){
$el.css({'position': 'static', 'top': '0px'});
}
});
When the scroll offset reached 200, the element will stick to the top of the browser window, because is placed as fixed.(当滚动偏移量达到200时,该元素将固定在浏览器窗口的顶部,因为它的位置固定。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…