Coo*_*ter 5 javascript css jquery
我正在尝试实现一个浮动在页面右下角的"go to top"按钮.我可以使用以下代码执行此操作,但我不希望此按钮进入我的页面的页脚.当用户将页面向下滚动到页面底部时,如何阻止它进入页脚并停留在页眉顶部?
CSS
#to-top {
position: fixed;
bottom: 10px;
right: 10px;
width: 100px;
padding: 5px;
border: 1px solid #ccc;
background: #f7f7f7;
color: #333;
text-align: center;
cursor: pointer;
display: none;
}
Run Code Online (Sandbox Code Playgroud)
JavaScript的
$(window).scroll(function() {
if($(this).scrollTop() != 0) {
$('#to-top').fadeIn();
} else {
$('#to-top').fadeOut();
}
});
$('#to-top').click(function() {
$('body,html').animate({scrollTop:0},"fast");
});
Run Code Online (Sandbox Code Playgroud)
HTML
<div id="to-top">Back to Top</div>
Run Code Online (Sandbox Code Playgroud)
编辑
下面是它应该是什么样子的图.黑色垂直矩形是滚动条."返回顶部"按钮不应进入页脚区域.

这是一个jsfiddle.
结果发现解决方案比我想象的要复杂。这是我的解决方案。
它使用此函数来检查页脚在屏幕上是否可见。如果是,它将按钮放置position: absolute在 div 内。否则,它使用position: fixed.
function isVisible(elment) {
var vpH = $(window).height(), // Viewport Height
st = $(window).scrollTop(), // Scroll Top
y = $(elment).offset().top;
return y <= (vpH + st);
}
$(window).scroll(function() {
if($(this).scrollTop() == 0) {
$('#to-top').fadeOut();
} else if (isVisible($('footer'))) {
$('#to-top').css('position','absolute');
} else {
$('#to-top').css('position','fixed');
$('#to-top').fadeIn();
}
});
Run Code Online (Sandbox Code Playgroud)