滚动到屏幕顶部后,如何使 div 贴在屏幕顶部? [英] How can I make a div stick to the top of the screen once it's been scrolled to?

查看:46
本文介绍了滚动到屏幕顶部后,如何使 div 贴在屏幕顶部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个 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.

这篇关于滚动到屏幕顶部后,如何使 div 贴在屏幕顶部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆