html - 在 IE 和页脚顶部使 div 具有粘性
问题描述
我想让一个 div 对滚动具有粘性,但是当它总是停留在页脚的顶部时。
我尝试使用position:sticky
which 工作正常,但它在 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
我该如何解决这个问题?
解决方案
不幸的是,我不知道有任何纯 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+。请记住,这是一个基本示例,您应该进行一些性能增强。
推荐阅读
- algorithm - 至少满足最小值差的列表元素的最大对数
- pointers - RC
> 进入 Rc > 使用不安全的指针 [停止关闭这不是重复的] - amazon-web-services - 如何将 aws pcluster 命令与 SSO 凭据一起使用?
- flutter - 活动以 resultCode 0 和计费的 responseCode: 4 结束
- python - 如何在 Python 中监听浏览器窗口中的事件
- xamarin.forms - Android 在启动 xamarin 表单后删除空白屏幕
- javascript - 在 Vscode 中编辑 Typescript 文件中的 css 代码时,所有文本都是红色的,我该如何解决这个问题?
- reporting-services - SSRS 将 IN 子句传递给 Redshift
- scala - 运行 AWS EMR Spark:java.io.FileNotFoundException ... io.netty_netty-transport-native-epoll-4.1.59.Final.jar 不存在
- java - 如何将我现有的两个 Android Studio 活动转换为两个片段,以便我可以制作导航栏?