首页 > 解决方案 > 在 IE 和页脚顶部使 div 具有粘性

问题描述

我想让一个 div 对滚动具有粘性,但是当它总是停留在页脚的顶部时。

我尝试使用position:stickywhich 工作正常,但它在 IE11 上不起作用。

我也为类似的问题尝试了多种解决方案,但他们总是提到如何使页脚变粘,而不是<div>main 中的另一个<div>

这就是我的代码的样子:

.slider {
  background: #006264;
  color: white;
  position: sticky;
  bottom: 0px;
  width: 100%;
  height: 60px;
}

.footer {
  background: #04246A;
  color: white;
  font-weight: bold;
  margin: 0 auto;
  height: 119px;
}
<div class="main">
  <div class="placeholder">This div holds place</div>
  <div class="placeholder">This div holds place</div>
  <div class="placeholder">This div holds place</div>
  <div class="placeholder">This div holds place</div>
  <div class="placeholder">This div holds place</div>
  <div class="slider">
    This is the footer
  </div>
</div>
<div class="footer">This is the main footer</div>

这是在JSFiddle

我该如何解决这个问题?

标签: htmlcssinternet-explorer-11sticky

解决方案


不幸的是,我不知道有任何纯 CSS 方法可以实现这种效果。但是,当然可以使用 JavaScript 和一些额外的 CSS。我在示例中使用了 jQuery,因为它更容易理解,但您当然可以将其转换为 JS。

$(window).scroll(function() {
  if ($(window).scrollTop() + $(window).height() > $('.footer').offset().top) {
    $('.main').removeClass('fixed');
  } else {
    $('.main').addClass('fixed');
  }
});

$(window).scroll();
/* resets */

body {
  margin: 0px;
  padding: 0px;
}

.main.fixed>.slider {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
}

.main.fixed~.footer {
  margin-top: 60px;
}

.slider {
  background: #006264;
  color: white;
  width: 100%;
  height: 60px;
}

.footer {
  background: #04246A;
  color: white;
  font-weight: bold;
  margin: 0 auto;
  height: 119px;
}

.placeholder {
  padding: 100px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="main fixed">
  <div class="placeholder">This div holds place</div>
  <div class="placeholder">This div holds place</div>
  <div class="placeholder">This div holds place</div>
  <div class="placeholder">This div holds place</div>
  <div class="placeholder">This div holds place</div>
  <div class="slider fixed">
    This is the footer
  </div>
</div>
<div class="footer">This is the main footer</div>

是的,它可以在 IE 中运行,因为 jQuery 仍然支持 IE9+。请记住,这是一个基本示例,您应该进行一些性能增强。


推荐阅读