2017-04-17 101 views
1

我有以下代码:页脚一旦用户滚动向上滑动到页面底部 - 闪烁

var footer = $('.footer'), 
    extra = 0; 

// footer.css({ opacity: '0', display: 'block' }); 


$(window).scroll(function() { 

    var scrolledLength = ($(window).height() + extra) + $(window).scrollTop(), 
     documentHeight = $(document).height(); 



    console.log('Scroll length: ' + scrolledLength + ' Document height: ' + documentHeight) 


    if(scrolledLength >= documentHeight) { 

     footer 
      .addClass('bottom') 
      // .slideUp(); 
      .stop().animate({ bottom: '0', opacity: '1' }, 300); 

    } 
    else if (scrolledLength <= documentHeight && footer.hasClass('bottom')) { 
     footer 
      .removeClass('bottom') 
      // .slideDown(); 
      .stop().animate({ bottom: '-100', opacity: '0' }, 300); 

    } 
}); 

我的目标是到页脚一旦用户滚动显示在页面的底部。如果用户再次向上滚动,我希望页脚再次滑下。

现在我正在检查scrolledLengthdocumentHeight。然而,问题似乎是,一旦我们达到最低点,documentHeight就会改变,因为页脚出现并扩展了文档。

我的代码确实有效,页脚不会再消失或任何东西,但它闪烁很多(然后最终平静下来),因为它正在重新计算。我怎么解决这个问题?我的代码中是否有错误?

+0

店如果页脚是可见的一个布尔值,如果是,计算高度documenth高度 - footerHeight? –

回答

1

您已经添加类到页脚,动画可以用CSS来处理:

.footer { 
    position: fixed; 
    width: 100%; 
    height: 100px; 
    bottom: -100px; 
    transition: all 200ms ease-out; 
} 

.footer.bottom { 
    bottom: 0; 
} 

更新:JSFiddle with working slide up footer

显然,我在猜测脚架应该如何设计,因为您还没有提供CSS - 当添加类.bottom时,此代码将简单地为页脚设置动画。

+0

谢谢。它不会弹出,但它似乎只是停留在底部并向下移动,但不会像现在这样出现在“无处”的位置。向后移动它看起来不错,但是消失了! –

+0

如果您可以在JSFiddle或Codepen上发布一个链接给您的代码,我可以进行相关更改。 – Toby

+0

非常感谢你。我以某种方式不能让它在这个jsfiddle中工作,但这是我的代码到目前为止:https://jsfiddle.net/u75d9pvc/1/我会再看看,并尝试让它在我的机器上工作,但从来没有使用jsfiddle之前,不知道发生了什么 –

1

尝试使用CSS过渡,而不是:

var footer = $('.footer'), 
 
    extra = 0; 
 

 
// footer.css({ opacity: '0', display: 'block' }); 
 

 

 
$(window).scroll(function() { 
 

 
    var scrolledLength = ($(window).height() + extra) + $(window).scrollTop(), 
 
     documentHeight = $(document).height(); 
 

 

 
    if(scrolledLength >= documentHeight) { 
 

 
     footer 
 
      .addClass('open') 
 
      
 
      
 

 
    } 
 
    else if (scrolledLength <= documentHeight && footer.hasClass('open')) { 
 
     footer 
 
      .removeClass('open') 
 
      
 

 
    } 
 
});
.container{ 
 
    position:relative; 
 
    height: 200vh; 
 
    width:100%; 
 
    background-color:red; 
 
    overflow:hidden; 
 
} 
 

 
.footer{ 
 
    height: 100px; 
 
    width:100%; 
 
    position: absolute; 
 
    left:0px; 
 
    bottom:-100px; 
 
    background-color: black; 
 
    transition: 1s; 
 
    
 
} 
 

 
.open{ 
 
    bottom:0px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="container"> 
 

 
    <div class="footer"></div> 
 
    
 
</div>