滚动到屏幕顶部后,如何使 div 贴在屏幕顶部?

2022-01-30 00:00:00 scroll jquery javascript css positioning

我想创建一个 div,它位于内容块下方,但一旦页面滚动到足以接触其顶部边界,它就会固定在适当的位置并随页面滚动.

I would like to create a div, that is situated beneath a block of content but that once the page has been scrolled enough to contact its top boundary, becomes fixed in place and scrolls with the page.

推荐答案

您可以使用简单的 css,将您的元素定位为 固定:

You could use simply css, positioning your element as fixed:

.fixedElement {
    background-color: #c0c0c0;
    position:fixed;
    top:0;
    width:100%;
    z-index:100;
}

你应该有绝对位置的元素,一旦滚动偏移到达元素,它应该被改为固定,顶部位置应该设置为零.

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.

您可以使用 scrollTop 函数检测文档的顶部滚动偏移:

You can detect the top scroll offset of the document with the scrollTop function:

$(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'}); 
  } 
});

当滚动偏移量达到 200 时,元素会粘到浏览器窗口的顶部,因为它是固定放置的.

When the scroll offset reached 200, the element will stick to the top of the browser window, because is placed as fixed.

相关文章