在右下角浮动div,但不在页脚内部

我正在尝试实现一个浮动在页面右下角的“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; } 

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

 
Back to Top

编辑下面是它应该是什么样子的图。 黑色垂直矩形是滚动条。 “返回顶部”按钮不应该进入页脚区域。 在此处输入图像描述

这是一个jsfiddle 。

事实certificate,解决方案比我想象的要复杂得多。 这是我的解决方案。

它使用此function检查屏幕上是否显示页脚。 如果是,则将按钮position: absolute为div position: absolute 。 否则,它使用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

增加bottom: 10px;的价值bottom: 10px; 比页脚的高度。 我现在看到了你的截图,只是添加了一些填充底部。

 $(document).ready(function(){ $(window).scroll(function(){ btnBottom = $(".btt").offset().top + $(".btt").outerHeight(); ftrTop = $(".footer").offset().top; if (btnBottom > ftrTop) $(".btt").css("bottom", btnBottom - ftrTop + $(".btt").outerHeight()); }); }); 

小提琴: http : //jsfiddle.net/praveenscience/BhvMg/


你忘了给z-index ,这可以防止它在顶部!

 z-index: 999; 

或者,如果它与页面的页脚重叠,则可以增加坐标。

 bottom: 50px; 

你的问题仍然不明确,“阻止它进入页脚”。 它重叠了吗?