首页 > 解决方案 > 滚动到该 div 后如何使 div 切换到底部固定?

问题描述

今天是个好日子。我试图在上下滚动时将我的 div 切换到底部的固定 div 。

我发现了这个堆栈溢出主题,它完成了我正在尝试做的事情,但在此处的顶部。

代码:

var fixmeTop = $('.fixme').offset().top;       // get initial position of the element

$(window).scroll(function() {                  // assign scroll event listener

    var currentScroll = $(window).scrollTop(); // get current position

    if (currentScroll >= fixmeTop) {           // apply position: fixed if you
        $('.fixme').css({                      // scroll to that element or below it
            position: 'fixed',
            top: '0',
            left: '0'
        });
    } else {                                   // apply position: static
        $('.fixme').css({                      // if you scroll above it
            position: 'static'
        });
    }

});

经过多次尝试和许多文章红色后,我无法将其调整为固定在底部(对 javascript 来说有点新)。所以我请求你的帮助。

标签: javascripthtmljquerycss

解决方案


你可以使用position: sticky

/*QuickReset*/ *{margin:0;box-sizing:border-box;}

.content {
  min-height: 200vh;
  border: 4px dashed #000;
}

.sticky-bottom {
  position: sticky;
  bottom: 0;
  padding: 2em 0;
  background: #0bf;
}
<div>
  <div class="content">
    1. Lorem ut florem...
  </div>
</div>

<div>
  <div class="content">
    2. Lorem ut florem...
  </div>
  <div class="sticky-bottom">Stick me when in viewport</div>
</div>


推荐阅读