我正在尝试实现一个浮动在页面右下角的“转到顶部”按钮。我可以使用以下代码来完成此操作,但我不希望此按钮进入我的页面的页脚。当用户将页面向下滚动到页面底部时,如何阻止它进入页脚并停留在页脚顶部?
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;
}
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");
});
HTML
<div id="to-top">Back to Top</div>
EDIT
Here is a drawing of how it should look like. The black vertical rectangle is a scroll bar. The "back to top" button should never enter the footer region.
这里有一个jsfiddle http://jsfiddle.net/emWMa/1/.
结果发现解决方案比我想象的要复杂。这是我的解决方案。
它使用这个function https://stackoverflow.com/questions/5353934/check-if-element-is-visible-on-screen/5354536#5354536检查页脚在屏幕上是否可见。如果是,则将按钮定位为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();
}
});
jsfiddle http://jsfiddle.net/3EzvR/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)