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

查看:297
本文介绍了如何在滚动到屏幕顶部后将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. I know I've seen at least one example of this online but I cannot remember it for the life of me.

任何想法?

推荐答案

您可以简单地使用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){ 
    $('.fixedElement').css({'position': 'fixed', 'top': '0px'}); 
  }
  if ($(this).scrollTop() < 200 && isPositionFixed)
  {
    $('.fixedElement').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天全站免登陆