当滚动到达某个div时,使div表现得像粘性一样

时间:2017-09-13 17:58:47

标签: javascript jquery

我有一个div元素包含动态文本到单词(10到250)。现在,当用户到达包含纯文本的第一个div的按钮时,我必须使另一个div表现得像粘性。这就是我如何尝试远。

   <div></div> //which contains plain text , stick to be available once user scroll to end of this.
   <div class="scroller_anchor"></div> // sticky to become when user reached to this div.
   <div> </div> // which one to behaves like sticky.
   //Here is code
   if(($(document).scrollTop() <$(".scroller_anchor").offset().top  ) ){
    $('.scroller_anchor').css('height', '0px');
    $('.scroller').css({
       'position': 'relative'
    });


  }else if ($(document).scrollTop() > ($(".scroller_anchor").offset().top )){
      $('.scroller').css({
            'position': 'fixed',
            'top': '0px'
        });
        $('.scroller_anchor').css('height', '50px');

  }

有了这一切工作正常,除了,div只有在用户滚动下面的firs div之后才会变粘。如果我使用$(document).scrollTop() <$(".scroller_anchor").offset().top -100它适用于某些文本(比如最多75个单词)。如何使factor (-100 , -220)等动态化。

1 个答案:

答案 0 :(得分:0)

计算scrollHeight,其行为类似于您的情况,下面是计算方法。

var scrollHeight =  window.innerHeight * (window.innerHeight / document.body.offsetHeight);

不同的浏览器行为略有不同。将100替换为scrollHeight。可能会有用。

相关问题