[英]How do I keep a div hidden when window is scrolled to top?
I have an up arrow that fades in when my page is scrolled down.当我的页面向下滚动时,我有一个向上箭头淡入。 How can I make it so that it fades out when the user scrolls back to the top of the page?
我怎样才能让它在用户滚动回页面顶部时淡出?
This is what I have so far.这是我到目前为止。 The arrow will disappear for a brief second then fade back in which I don't want - it should stay hidden.
箭头将消失一秒钟,然后淡出我不想要的 - 它应该保持隐藏状态。
function footerFadeIn() { $(window).scroll(function() { $('footer').fadeIn('slow'); }); } function footerFadeOut() { $('footer').fadeOut('slow'); $('footer').hide(); } $(window).scroll(function() { if ($(window).scrollTop() == 0) { footerFadeOut(); } else if ($(window).scrollTop() > 0) { footerFadeIn(); } });
footer { position: fixed; bottom: 0; right: 0; padding: 20px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <footer> <i class="fas fa-chevron-up" style="font-size: 35px;"></i> </footer>
My thought process here is to have two functions - footerFadeIn()
and footerFadeOut()
.我在这里的思考过程是有两个函数 -
footerFadeIn()
和footerFadeOut()
。 Then I have an if statement that checks if the window is scrolled away from scrollTop() of zero and executes the respective function.然后我有一个 if 语句,用于检查窗口是否从 scrollTop() 为零并执行相应的函数。
EDIT: My question differs from the suggested one in that I simply had two event handlers that were causing the issue.编辑:我的问题与建议的问题不同,因为我只有两个导致问题的事件处理程序。
The issue is because you have added a scroll event handler inside footerFadeIn()
.问题是因为您在
footerFadeIn()
添加了滚动事件处理程序。 As such you end up creating another new scroll event handler when a scroll event happens.因此,当滚动事件发生时,您最终会创建另一个新的滚动事件处理程序。 To fix this, just remove the scroll handler in that function and leave the main one which is called when the DOM loads.
要解决此问题,只需删除该函数中的滚动处理程序并保留在 DOM 加载时调用的主要处理程序。
Also note that you need to call hide()
in the callback of fadeOut()
.另请注意,您需要在
fadeOut()
的回调中调用hide()
fadeOut()
。 This is why the fadeout animation doesn't happen correctly.这就是淡出动画没有正确发生的原因。 Try this:
尝试这个:
function footerFadeIn() { $('footer').fadeIn('slow'); } function footerFadeOut() { $('footer').fadeOut('slow', function() { $(this).hide(); }); } $(window).scroll(function() { if ($(window).scrollTop() == 0) { footerFadeOut(); } else if ($(window).scrollTop() > 0) { footerFadeIn(); } });
html, body { height: 2000px; } footer { position: fixed; bottom: 0; right: 0; padding: 20px; display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.css" /> <footer> <i class="fas fa-chevron-up" style="font-size: 35px;"></i> </footer>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.