粘性元素在到达元素时停止

时间:2019-05-24 12:43:54

标签: javascript jquery css sticky boundary

当我滚动并到达另一个元素的顶部时,我想制作一个固定元素(如粘性)。固定元素将增加css的bottom属性,以不超过我设置为绑定的元素的顶部(您不能通过该点的元素,例如地面)。我用钢笔显示了我想要的东西,希望对您有所帮助:https://codepen.io/vendramini/pen/xNWpPK。我真的不知道要实现这个目标需要做哪些计算。请帮帮我。

https://codepen.io/vendramini/pen/xNWpPK 我能做的最好的例子就是这样。


*{
  margin: 0;
  padding: 0;
}

section{
  height: 100vh;
  width: 100vw;
  background: #eee;
  position: relative;
  max-width: 100%;
}

.a{
  background: #faa;
}

.b{
  background: #ffa;
}

.c{
  background: #afa;
}

.d{
  background: #aaf;
}

.sticky{
  width: 100%;
  position: fixed;
  height: 100px;
  background: blue;
  opacity: 0.5;
  bottom: 0;
  z-index: 1;
}

.ground{
    height: 2000px;
    background: black;
}
//jQuery required

(function($){

  $('[data-bound]').each(function(){

    const $elem = $(this);
    const $bound = $( $elem.data('bound') );

    $(window).scroll(function(){

      const scrollTop = $(window).scrollTop();
      const boundTop = $bound.offset().top;
      const boundHeight = $bound.height();
      const delta = (scrollTop - boundTop); //+ boundHeight;

      console.log({
        scrollTop,
        boundTop,
        delta,
      });

      if( delta > 0 ){
        $elem.css('bottom', delta);
      }
      else{
        $elem.removeAttr('style');
      }

    });


  });

})(jQuery);

<div class="sticky" data-bound="#ground"></div>

<section class="a"></section>
<section class="b"></section>
<section class="c"></section>
<section class="d"></section>
<footer class="ground" id="ground"></footer>
<section class="a"></section>
<section class="b"></section>
<section class="c"></section>
<section class="d"></section>


我希望有一个固定的元素不通过地面元素。就是这样。

4 个答案:

答案 0 :(得分:1)

我终于找到了答案:

https://codepen.io/vendramini/pen/xNWpPK

解决方案是将窗口的高度添加到增量计算中:

const windowHeight = $(window).height();
const delta = (scrollTop - boundTop) + windowHeight;

感谢所有对此线程做出贡献的人!

答案 1 :(得分:0)

替换

      if( delta > 0 ){
        $elem.css('bottom', delta);
      }
      else{
        $elem.removeAttr('style');
      }

$elem.css('bottom', 0);

将元素始终粘贴在底部。

答案 2 :(得分:0)

我不确定我确切地了解您想要什么,但是我认为仅使用CSS在页脚上使用position: sticky即可实现。

https://codepen.io/anon/pen/jozzPq

相关人员更改:

为带有粘性页脚的元素添加包装器:

<div>
  <section class="a"></section>
  <section class="b"></section>
  <section class="c"></section>
  <section class="d"></section>
  <footer class="ground" id="ground">   </footer>
</div>

将页脚置于底部并将其设置为粘性

.ground{
    height: 100px;
    background: black;
    position: sticky;
    bottom: 0;
}

检查代码笔是否导致大量CSS和(所有)JS可以删除。

答案 3 :(得分:-1)

我想要的是UIKit旁边的东西: https://getuikit.com/docs/sticky

但是问题是UIKit使用top而不是bottom。

相关问题