代码之家  ›  专栏  ›  技术社区  ›  Yudy Ananda

基于多事件的jQuery滚动函数

  •  0
  • Yudy Ananda  · 技术社区  · 8 年前

    div

    <main>
       <header id="foo"></header>
       <article id="bar"></bar>
       <div id="someDiv"></div>
       <div id="stickyDiv"></div>
       <footer id="bikiniBottom"></footer>
    

    stickyDiv 是粘在页面底部的元素。只有当用户使用javascript向下滚动页面时才会出现,当用户滚动到顶部时,它就会消失

    var prevScrollpos = window.pageYOffset;
            window.onscroll = function() {
            var currentScrollPos = window.pageYOffset;
            if (prevScrollpos < currentScrollPos) {
                document.getElementById("stickyDiv").style.bottom = "0";
            } else {
                document.getElementById("stickyDiv").style.bottom = "-80px";
            }
            prevScrollpos = currentScrollPos;
            }
    

    bar 元素在到达页脚之前再次解体

    1 回复  |  直到 8 年前
        1
  •  0
  •   cdoshi    8 年前

    这取决于你所说的到达bar元素是什么意思。我假设你的意思是,当条到达顶部时,显示页脚并隐藏页脚,然后条就消失了。我已经包括了一个范围,因为有时滚动位置可能会错过,如果用户快速滚动。随时根据您的需要进行调整

    你可以做些类似的事情,

    var $el = $('#bar');
    var top = $el.position().top;
    var bottom = top + $el.height();
    if(Math.abs(top - $(window).scrollTop()) < 5) {    
       console.log('Bar is at the top');
       document.getElementById("stickyDiv").style.bottom = "0";
    } 
    
    if(Math.abs(bottom - $(window).scrollTop()) < 5) {
       console.log('Bar went out of view');
      document.getElementById("stickyDiv").style.bottom = "-80px";
    }