您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

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

您应该将元素的位置设为绝对,一旦滚动偏移量到达该元素,则应将其更改为fixed,并将顶部位置设置为零。

您可以使用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'}); 
  } 
});

当滚动偏移量达到200时,该元素将 固定 在浏览器窗口的顶部,因为它被固定放置。

其他 2022/1/1 18:17:30 有539人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶