简体   繁体   中英

Float a div at the bottom right corner, but not inside footer

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

$(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. 在此输入图像描述

Here is a jsfiddle .

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

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

Increase the value of bottom: 10px; than the height of footer. I saw your screenshot now,just add some padding-bottom to it.

Solution

$(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());
    });
});

Fiddle: http://jsfiddle.net/praveenscience/BhvMg/


You forgot to give the z-index , that prevents it from being on top!

z-index: 999;

Or if it is overlapping with the footer of your page, you can increase the co-ordinates.

bottom: 50px;

Your question is still not clear, "stop it from entering the footer". Does it overlap?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM