在页脚处停止固定位置

时间:2011-12-28 07:19:58

标签: javascript jquery css scroll fixed

我正在寻找在页面页脚停止固定对象的流行问题的解决方案。

我基本上在屏幕的左下角有一个固定的“共享”框,我不希望它滚动页脚,所以我需要它停在页脚上方10px左右。 / p>

我在这里和其他人一样看过其他问题。我能找到的最接近/最简单的演示是http://jsfiddle.net/bryanjamesross/VtPcm/,但我无法使用它来处理我的情况。

这是共享框的html:

    <div id="social-float">
        <div class="sf-twitter">
            ...
        </div>

        <div class="sf-facebook">
            ...
        </div>

        <div class="sf-plusone">
            ...
        </div>
    </div>

...和CSS:

#social-float{
position: fixed;
bottom: 10px;
left: 10px;
width: 55px;
padding: 10px 5px;
text-align: center;
background-color: #fff;
border: 5px solid #ccd0d5;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px;
display: none;
}

页脚为#footer,并且没有固定的高度,如果这有任何不同。

如果有人可以帮助我为此创建一个简单的jQuery解决方案,我会非常感激!

13 个答案:

答案 0 :(得分:55)

Live demo

首先,每次滚动页面时检查其偏移量

$(document).scroll(function() {
    checkOffset();
});

并且如果它在页脚之前被击倒在10px以下,则使其位置绝对。

function checkOffset() {
    if($('#social-float').offset().top + $('#social-float').height() 
                                           >= $('#footer').offset().top - 10)
        $('#social-float').css('position', 'absolute');
    if($(document).scrollTop() + window.innerHeight < $('#footer').offset().top)
        $('#social-float').css('position', 'fixed'); // restore when you scroll up
}

请注意#social-float的父级应该是页脚的兄弟

<div class="social-float-parent">
    <div id="social-float">
        something...
    </div>
</div>
<div id="footer">
</div>
祝你好运:)

答案 1 :(得分:20)

我刚刚在我正在处理的网站上解决了这个问题,并且认为我会分享它,希望能帮助某人。

我的解决方案是从页脚到页面顶部的距离 - 如果用户滚动得比这更远,它会以负边距拉回侧边栏。

$(window).scroll(() => { 
  // Distance from top of document to top of footer.
  topOfFooter = $('#footer').position().top;
  // Distance user has scrolled from top, adjusted to take in height of sidebar (570 pixels inc. padding).
  scrollDistanceFromTopOfDoc = $(document).scrollTop() + 570;
  // Difference between the two.
  scrollDistanceFromTopOfFooter = scrollDistanceFromTopOfDoc - topOfFooter;

  // If user has scrolled further than footer,
  // pull sidebar up using a negative margin.
  if (scrollDistanceFromTopOfDoc > topOfFooter) {
    $('#cart').css('margin-top',  0 - scrollDistanceFromTopOfFooter);
  } else  {
    $('#cart').css('margin-top', 0);
  }
});

答案 2 :(得分:4)

我最近遇到了同样的问题,在这里发布了我的解决方案: Preventing element from displaying on top of footer when using position:fixed

您可以使用jQuery利用元素的position属性实现解决方案,在默认值(static divs),fixed和{{1}之间切换}}。 您还需要一个容器元素作为固定元素。最后,为了防止固定元素越过页脚,此容器元素不能是页脚的父元素。

javascript部分涉及计算固定元素与文档顶部之间的像素距离,并将其与滚动条相对于窗口对象的当前垂直位置(即上面隐藏的像素数)进行比较每次用户滚动页面时,页面的可见区域。 当向下滚动时,固定元素即将消失,我们将其位置更改为固定并粘贴在页面顶部。

当我们滚动到底部时,这会导致固定元素越过页脚,特别是如果浏览器窗口很小。 因此,我们将从文档顶部计算页脚的像素距离,并将其与固定元素的高度加上滚动条的垂直位置进行比较:当固定元素即将越过页脚时,我们将将其位置更改为绝对位置并粘贴在底部,就在页脚上方。

这是一个通用的例子。

HTML结构:

absolute

CSS:

<div id="content">
    <div id="leftcolumn">
        <div class="fixed-element">
            This is fixed 
        </div>
    </div>
    <div id="rightcolumn">Main content here</div>
    <div id="footer"> The footer </div>
</div>  

JS:

#leftcolumn {
    position: relative;
}
.fixed-element {
    width: 180px;
}
.fixed-element.fixed {
    position: fixed;
    top: 20px;
}
.fixed-element.bottom {
    position: absolute;
    bottom: 356px; /* Height of the footer element, plus some extra pixels if needed */
}

答案 3 :(得分:4)

这是@Sang解决方案,但没有Jquery。

&#13;
&#13;
var socialFloat = document.querySelector('#social-float');
var footer = document.querySelector('#footer');

function checkOffset() {
  function getRectTop(el){
    var rect = el.getBoundingClientRect();
    return rect.top;
  }
  
  if((getRectTop(socialFloat) + document.body.scrollTop) + socialFloat.offsetHeight >= (getRectTop(footer) + document.body.scrollTop) - 10)
    socialFloat.style.position = 'absolute';
  if(document.body.scrollTop + window.innerHeight < (getRectTop(footer) + document.body.scrollTop))
    socialFloat.style.position = 'fixed'; // restore when you scroll up
  
  socialFloat.innerHTML = document.body.scrollTop + window.innerHeight;
}

document.addEventListener("scroll", function(){
  checkOffset();
});
&#13;
div.social-float-parent { width: 100%; height: 1000px; background: #f8f8f8; position: relative; }
div#social-float { width: 200px; position: fixed; bottom: 10px; background: #777; }
div#footer { width: 100%; height: 200px; background: #eee; }
&#13;
<div class="social-float-parent">
    <div id="social-float">
        float...
    </div>
</div>
<div id="footer">
</div>
&#13;
&#13;
&#13;

答案 4 :(得分:2)

这对我有用 -

HTML -

<div id="sideNote" class="col-sm-3" style="float:right;">

</div> 
<div class="footer-wrap">
        <div id="footer-div">
        </div>      
</div>

CSS -

#sideNote{right:0; margin-top:10px; position:fixed; bottom:0; margin-bottom:5px;}

#footer-div{margin:0 auto; text-align:center; min-height:300px; margin-top:100px; padding:100px 50px;}

JQuery -

function isVisible(elment) {
    var vpH = $(window).height(), // Viewport Height
        st = $(window).scrollTop(), // Scroll Top
        y = $(elment).offset().top;

    return y <= (vpH + st);
}

function setSideNotePos(){
    $(window).scroll(function() {
        if (isVisible($('.footer-wrap'))) {
            $('#sideNote').css('position','absolute');
            $('#sideNote').css('top',$('.footer-wrap').offset().top - $('#sideNote').outerHeight() - 100);
        } else {
            $('#sideNote').css('position','fixed');
            $('#sideNote').css('top','auto');
        }
    });
}

现在像这样调用这个函数 -

$(document).ready(function() {
    setSideNotePos();
});

PS - Jquery函数从stackoverflow上的另一个类似问题的答案复制,但它并没有完全适用于我。所以我将它修改为这些函数,如这里所示。我认为你的div的位置等属性将取决于div的结构,他们的父母和兄弟姐妹是谁。

当sideNote和footer-wraps都是直接兄弟姐妹时,上述功能有效。

答案 5 :(得分:1)

您现在可以使用

#myObject{
  position:sticky;
}

希望这会有所帮助。

答案 6 :(得分:1)

现在可以用 position: sticky 完成。

body,
html {
  height: 100%;
}

body {
  background-color: linen;
  margin: 0;
}


body,
main {
  display: flex;
  flex-direction: column;
}

main,
section {
  flex: 1;
}

main {
  min-height: 200vh;
}

.sticky {
  position: sticky;
  top: 0;
  background-color: lightcoral;
  padding: 1rem;
}

p {
  padding: 0 1rem;
}

footer {
  background-color: lightblue;
  padding: 15rem 1rem;
}
<main>
  <section>
    <div class="sticky">
      <h2>I am sticky<h2>
    </div>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>

  <p>Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod in, nibh. Quisque volutpat condimentum velit. </p>

  <p>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis turpis. Nulla facilisi. Ut fringilla. Suspendisse potenti. Nunc feugiat mi a tellus consequat imperdiet. Vestibulum sapien. Proin quam. Etiam ultrices. Suspendisse in justo eu magna luctus suscipit. Sed lectus. Integer euismod lacus luctus magna. Quisque cursus, metus vitae pharetra auctor, sem massa mattis sem, at interdum magna augue eget diam. </p>

  <p>Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi lacinia molestie dui. Praesent blandit dolor. Sed non quam. In vel mi sit amet augue congue elementum. Morbi in ipsum sit amet pede facilisis laoreet. Donec lacus nunc, viverra nec, blandit vel, egestas et, augue. Vestibulum tincidunt malesuada tellus. Ut ultrices ultrices enim. Curabitur sit amet mauris. Morbi in dui quis est pulvinar ullamcorper. Nulla facilisi. Integer lacinia sollicitudin massa. </p>

  <p>Cras metus. Sed aliquet risus a tortor. Integer id quam. Morbi mi. Quisque nisl felis, venenatis tristique, dignissim in, ultrices sit amet, augue. Proin sodales libero eget ante. Nulla quam. Aenean laoreet. Vestibulum nisi lectus, commodo ac, facilisis ac, ultricies eu, pede. Ut orci risus, accumsan porttitor, cursus quis, aliquet eget, justo. Sed pretium blandit orci. Ut eu diam at pede suscipit sodales. Aenean lectus elit, fermentum non, convallis id, sagittis at, neque. Nullam mauris orci, aliquet et, iaculis et, viverra vitae, ligula. </p>
  </section>
  <footer>
    <h2>I am a footer<h2>
  </footer>
</main>

答案 7 :(得分:0)

我修改了@ user1097431的回答:

function menuPosition(){
// distance from top of footer to top of document
var footertotop = ($('.footer').position().top);
// distance user has scrolled from top, adjusted to take in height of bar (42 pixels inc. padding)
var scrolltop = $(document).scrollTop() + window.innerHeight;
// difference between the two
var difference = scrolltop-footertotop;

// if user has scrolled further than footer,
// pull sidebar up using a negative margin
if (scrolltop > footertotop) {
    $('#categories-wrapper').css({
       'bottom' : difference
   });
}else{
    $('#categories-wrapper').css({
       'bottom' : 0
   });
 };
};

答案 8 :(得分:0)

($PrintDocument.PrinterSettings | gm -MemberType Property ).Name -join ','

CanDuplex,Collate,Copies,DefaultPageSettings,Duplex,FromPage,IsDefaultPrinter,IsPlotter,IsValid,LandscapeAngle,MaximumCopies,MaximumPage,MinimumPage,PaperSizes,PaperSources,PrinterName,PrinterResolutions,PrintFileName,PrintRange,PrintToFile,SupportsColor,ToPage

答案 9 :(得分:0)

纯CSS解决方案

<div id="outer-container">
    <div id="scrollable">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam in vulputate turpis. Curabitur a consectetur libero. Nulla ac velit nibh, ac lacinia nulla. In sed urna sit amet mauris vulputate viverra et et eros. Pellentesque laoreet est et neque euismod a bibendum velit laoreet. Nam gravida lectus nec purus porttitor porta. Vivamus tempor tempus auctor. Nam quis porttitor ligula. Vestibulum rutrum fermentum ligula eget luctus. Sed convallis iaculis lorem non adipiscing. Sed in egestas lectus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nunc dictum, lacus quis venenatis ultricies, turpis lorem bibendum dui, quis bibendum lacus ante commodo urna. Fusce ut sem mi, nec molestie tortor. Mauris eu leo diam. Nullam adipiscing, tortor eleifend pellentesque gravida, erat tellus vulputate orci, quis accumsan orci ipsum sed justo. Proin massa massa, pellentesque non tristique non, tristique vel dui. Vestibulum at metus at neque malesuada porta et vitae lectus.
    </div>
    <button id="social-float">The button</button>
</div>
<div>
Footer
</div>
</div>

这里有CSS

#outer-container {
    position: relative;
}

#scrollable {
    height: 100px;
    overflow-y: auto;
}

#social-float {
    position: absolute;
    bottom: 0px;
}

答案 10 :(得分:0)

我对第二受欢迎的答案进行了一些更改,因为我发现这对我来说更好。更改使用window.innerHeight,因为它比添加您自己的导航高度(上面使用的+ 570)更具动态性。这使代码可以动态地在移动设备,平板电脑和台式机上运行。

$(window).scroll(() => {
            //Distance from top fo document to top of footer
            topOfFooter = $('#footer').position().top;
             // Distance user has scrolled from top + windows inner height
             scrollDistanceFromTopOfDoc = $(document).scrollTop() + window.innerHeight;
             // Difference between the two.
             scrollDistanceFromTopOfFooter = scrollDistanceFromTopOfDoc - topOfFooter; 
            // If user has scrolled further than footer,
              if (scrollDistanceFromTopOfDoc > topOfFooter) {
                // add margin-bottom so button stays above footer.
                $('#floating-button').css('margin-bottom',  0 + scrollDistanceFromTopOfFooter);
              } else  {
                // remove margin-bottom so button goes back to the bottom of the page
                $('#floating-button').css('margin-bottom', 0);
              }
            });

答案 11 :(得分:0)

我正在努力在页脚之前的某个时刻停止Adbanner。并使用了我在上面找到的代码。

为我工作(横幅在页脚之前消失,并重新出现在滚动到顶部的位置):

<style>
#leftsidebanner {width:300px;height:600px;position: fixed; padding: 0;top:288px;right:5%;display: block;background-color: aqua}
</style>

<div id="leftsidebanner">
</div>


<script>

    $.fn.followTo = function (pos) {
    var stickyAd = $(this),
    theWindow = $(window);
    $(window).scroll(function (e) {
      if ($(window).scrollTop() > pos) {
        stickyAd.css({'position': 'absolute','bottom': pos});
      } else {
        stickyAd.css({'position': 'fixed','top': '100'});
      }
    });
  };
  $('#leftsidebanner').followTo(2268);


</script>

答案 12 :(得分:0)

如果元素出现故障,这可能是因为当您将位置更改为relative时,页脚的Y位置会增加,这会尝试将项目发送回fixed,从而创建循环。您可以通过在上下滚动时设置两种不同的情况来避免这种情况。您甚至不需要引用固定元素,只需引用页脚和窗口大小即可。

const footer = document.querySelector('footer');
document.addEventListener("scroll", checkScroll);

let prevY = window.scrollY + window.innerHeight;
function checkScroll() {
  let footerTop = getRectTop(footer) + window.scrollY;
  let windowBottomY = window.scrollY + window.innerHeight;
  if (prevY < windowBottomY) {  // Scroll Down
    if (windowBottomY > footerTop)
      setScrolledToFooter(true) // using React state. Change class or change style in JS.
  } else { // Scroll Up
    if (windowBottomY <= footerTop)
      setScrolledToFooter(false)
  }
  prevY = windowBottomY
};

function getRectTop(el) {
  var rect = el.getBoundingClientRect();
  return rect.top;
}

以及元素在样式对象中的位置,如下所示:

position: scrolledToFooter ? 'relative' : 'fixed'