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

我试图实现浮动在页面右下角的“返回顶部”按钮。 我可以用下面的代码来做到这一点,但我不想让这个按钮进入我的页面的页脚。 当用户将页面向下滚动到页面底部时,如何阻止页面进入页脚并保持在页面的顶部?

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>

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

这是一个jsfiddle。


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

它使用此功能来检查页脚是否在屏幕上可见。 如果是,它将位置position: absolute的按钮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


增加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;

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

链接地址: http://www.djcxy.com/p/83595.html

上一篇: Float a div at the bottom right corner, but not inside footer

下一篇: How to select an element that has focus on it with jQuery