在右下角浮动div,但不在页脚内部 [英] Float a div at the bottom right corner, but not inside footer

查看:77
本文介绍了在右下角浮动div,但不在页脚内部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个浮动在页面右下角的go to top按钮。我可以使用以下代码执行此操作,但我不希望此按钮进入我的页面的页脚。当用户将页面向下滚动到页面底部时,如何阻止它进入页脚并保持在页面顶部?

I'm trying to implement a "go to top" button that floats at the bottom right corner of a page. I can do this with the following code, but I don't want this button to enter the footer of my page. How can I stop it from entering the footer and stay at the top of it when user scrolls the page down to the bottom of the page?

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

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

推荐答案

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

The solution turned out to be more complicated than I thought. Here is my solution.

它使用功能检查页脚是否在屏幕上可见。如果是,它会在div中以 position:absolute 定位按钮。否则,它使用 position:fixed

It uses this function to check if footer is visible on the screen. If it is, it positions the button with position: absolute within a div. Otherwise, it uses 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

jsfiddle

这篇关于在右下角浮动div,但不在页脚内部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆