DIV出现在向上滚动控制位置

时间:2018-08-20 21:28:13

标签: javascript jquery html css

我有一个DIV栏,它在加载时显示在屏幕的底部,当用户向下滚动时消失,而当用户返回顶部时重新出现。我想控制DIV在向上滚动时何时重新出现。我怎样才能做到这一点?

HTML

<div id="bottom-cta">
  <a href="/join">Get Started!</a>
</div>

CSS

#bottom-cta {
  background-color: #3bb618;
  text-align: center;
  padding: 11px 0 11px;
  text-transform: uppercase;
  position: fixed;
  bottom: 0;
  width: 100%;
  z-index: 9999;
  height: 60px;
  transition: bottom 0.1s ease-in-out;
  -webkit-transition: bottom 0.1s ease-in-out;
  -moz-transition: bottom 0.1s ease-in-out;
  -ms-transition: bottom 0.1s ease-in-out;
  -otransition: bottom 0.1s ease-in-out;
}
#bottom-cta a {
  color: #fff;
  font-size: 28px;
  font-weight: 700;
  display: inline-block;
}

jQuery

var $element = $('#bottom-cta');

$(window).scroll(function() {

if($(this).scrollTop() > 0) {
    $element.fadeOut();
} else {
    $element.fadeIn();
}
});

提琴

http://jsfiddle.net/6usogk7z/

1 个答案:

答案 0 :(得分:0)

您可以将window的当前滚动位置存储在变量中,并检查window滚动时滚动位置是否大于(用户向下滚动)以隐藏{页脚,否则显示页脚(因为用户向上滚动)。

var $element = $('#bottom-cta');
var prevYPos = $(window).scrollTop();//current window scroll position
$(window).scroll(function() {
    var currentYPos = $(this).scrollTop();
    if(currentYPos > prevYPos) {
        $element.fadeOut();
    } else {
        $element.fadeIn(0);
    }
    prevYPos = currentYPos;//set the previous scroll position to the scroll position when the window is scrolled
});
#bottom-cta {
background-color: #3bb618;
text-align: center;
padding: 11px 0 11px;
text-transform: uppercase;
position: fixed;
bottom: 0;
width: 100%;
z-index: 9999;
height: 60px;
transition: bottom 0.1s ease-in-out;


}
#bottom-cta a {
color: #fff;
font-size: 28px;
font-weight: 700;
display: inline-block;
}

body { 
height: 2000px; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bottom-cta">
<a href="/join">Get Started!</a>
</div>