完全滚动后的粘贴页脚

问题描述 投票:0回答:3

我正在尝试创建位于页面底部的“另请参阅”按钮。当用户到达底部并决定向上滚动时,我希望它粘贴到视口的底部。

我一直在尝试使用position:sticky,但是当页面刚刚加载时,它已经被粘在视口的底部。我只想在完全向下滚动后才能看到。

任何线索?预先感谢。

html css footer sticky
3个回答
1
投票

这是一个使用javascript的示例(请参见结果sticky button on scroll top

const DIRECTION_BOTTOM = 1;
const DIRECTION_TOP = 0;

let previousScroll = 0;
let direction = scrollY === 0 ? DIRECTION_BOTTOM : DIRECTION_TOP;

window.addEventListener('scroll', function(){
    const scrollY = window.scrollY;

    if(direction === DIRECTION_TOP && previousScroll < scrollY){
        direction = DIRECTION_BOTTOM;

        // remove sticky
        document.getElementById("sticky").classList.remove("show");
    }
    else if(direction === DIRECTION_BOTTOM && previousScroll > scrollY ){
        direction = DIRECTION_TOP;

        // Add sticky 
        document.getElementById("sticky").classList.add("show");
    }

    previousScroll = scrollY;
})

0
投票

您可以通过创建一个计算元素何时在视口中的函数来使用JQuery创建此功能。如果按钮进入视口,则添加一个使元素位置处于粘滞状态的类。解决此问题的方法有多种,但一种解决方案是这样的:

$.fn.isInViewport = function() {
    var elementTop = $(this).offset().top;
    var elementBottom = elementTop + $(this).outerHeight();

    var viewportTop = $(window).scrollTop();
    var viewportBottom = viewportTop + $(window).height();

    return elementBottom > viewportTop && elementTop < viewportBottom;
};
  

  
 $(window).on("scroll", function() {
    if($('#button').isInViewport()) {
        $('#button').addClass('sticky');
    }
 });
body {
  text-align: center;
}

.button {
  padding: 6px 12px;
}

.div {
  width: 100%;
  height: 250px;
  color: #fff;
}

.div1 {
  background: blue;
}
.div2 {
  background: red;
 }
 .div3 {
  background: purple;
 }
 
 .sticky {
  position: sticky;
  position: -webkit-sticky;
  position: -moz-sticky;
  position: -ms-sticky;
  position: -o-sticky;
  height: 100%;
  bottom: 5px;
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<div class="div div1">Filler div 1</div>
<div class="div div2">Filler div 2</div>
<div class="div div3">Filler div 3</div>

<button type="button" class="button" id="button">See Also</button>

-1
投票

转到css并添加到页脚z-index: -1;,以便在加载页面时页脚没有层定位特权,然后向下滚动时转到javascript并将其更改为z-index: 1000,因此它具有绝对层定位特权

如果我是你,我也会添加transition,也许还会添加一些translateX,所以当页脚出现时,会有一些动画效果

© www.soinside.com 2019 - 2024. All rights reserved.