我有一个联系按钮,它位于两个内容项之间的屏幕可见部分。一旦用户向下滚动,我希望按钮固定在屏幕的底部,这样它就始终在视线范围内。
var pos = $('#test').scrollTop();
if (pos > 200) $('#test').addclass('fixed')
console.log(pos)
.fixed {
bottom: 0px;
position: fixed;
width: 100%;
height: 50px;
background-color: red;
}
#test {
background-color: red;
}
#content {
height: 100px;
background: green;
}
#content2 {
height: 1000px;
background: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<div id="content"></div>
<div id="test">button</div>
<div id="content2"></div>
问题是要知道按钮什么时候会消失,以便附加固定功能。
如何做到这一点?
最佳答案
您可以使用 .offsetTop
来实现。所以添加这个,它会使用你的类 fixed
来做你需要的。
var fixButton = document.getElementById("test");
var sticky = fixButton.offsetTop;
window.onscroll = function() {
if (window.pageYOffset > sticky) {
fixButton.classList.add("fixed");
} else {
fixButton.classList.remove("fixed");
}
}
关于javascript - 滚动后如何将div保持在屏幕底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55891011/