我有一个带有position:fixed,bottom:0px的元素。
当我向下滚动页面时,该元素应该跟随我直到它靠近页脚(假设高度为100px),我试图允许该元素停留在bottom:0px处,直到到达页脚元素为止,在那一刻应该始终让页脚元素位于其下方。
这是我的CSS:
#backToTop{
width:80px;
height:50px;
background:#333;
color:#FFF;
text-align:center;
border-radius:10px 10px 0 0;
padding-top:10px;
position:fixed;
bottom:0;
left:50%;
margin-left:550px;
}
我研究了Jquery的
$(document).height()
和$(window).scrollTop()
尝试提出某种条件,该条件将检测元素的位置何时靠近页脚,但没有成功(页脚的高度为120):$(window).scroll(function(){
if($(document).height()-($(window).scrollTop()+$(window).height()) <= 120){
$('#backToTop').css({'bottom':$(document).height()-($(window).scrollTop()+$(window).height())});
}else{
$('#backToTop').css('bottom',0);
}
});
我不太确定这些值到底指向什么,有什么提示吗?谢谢。
最佳答案
尝试为#backToTop元素创建两个类,一个为固定类,另一个为相对位置。当页脚到达视口时,#backToTop元素将其类更改为“相对”。
HTML:
<div id="container">
<div id="backToTop" class="fixed_pos">Top</div>
<footer>footer</footer>
</div>
CSS:
#container {
width: 100%;
height: 1000px;
float: left;
}
#backToTop {
width:80px;
height:50px;
background:#333;
color:#FFF;
text-align:center;
border-radius:10px 10px 0 0;
padding-top:10px;
left: 50%;
margin-left: -40px;
}
.fixed_pos {
position:fixed;
bottom:0;
}
.relative_pos {
position: relative;
top: 100%;
}
footer {
width: 100%;
height: 200px;
float: left;
position: relative;
top: 100%;
background: #333;
color: #fff;
text-align: center;
}
在这里看看:
http://jsfiddle.net/6bZab/
关于jquery - 如何使固定元素与文档底部保持特定距离?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16129543/