2017-08-11 90 views
0

我无法使用scrolltop()函数触发一个动画与CSS。我想要文本'向下滚动以更改效果'隐藏并显示两个按钮,当用户向下滚动到70像素。但是这个功能似乎不起作用。我是否必须使用偏移来触发动画?请帮忙,我想熟悉jQuery和动画CSS。如何使用滚动顶部在CSS中触发动画?

这里是我下面的代码:

$(document).ready(function(){ 
 
     if ($(window).scrollTop() > 70) 
 
     { 
 
     $('.process h2').hide(); 
 
     $('.process a').show(); 
 

 
     } 
 
     else { 
 
      $('.process h2').show(); 
 
      $('.process a').hide(); 
 
     } 
 
    });
h1,h2,h3,h4,h5,h6 {margin: 0;} 
 
    a {text-decoration: none;color: #2aabcc;} 
 
    body {background: #f3f3f3;height: 1200px;} 
 
    .container {width: 1000px;max-width: 100%;position: relative;margin: 0 auto;padding: 0;} 
 
    .page_header {overflow: hidden;} 
 
    .page_header h1 {text-align: center;position: relative;animation: pagetitle 1.5s;} 
 
    .process {text-align: center;padding: 30px 10px;} 
 
    .process a {color: #000;display: inline-block;line-height: 44px;border: 1px solid #000;margin: 0 auto;width: 150px;height: 44px;text-align: center;} 
 
    .process a:hover {color: #b51e1e;border: 1px solid #b51e1e;} 
 
    @keyframes pagetitle { 
 
     0%{transform: translateY(-81%);opacity: 0;} 
 
     50% {opacity: 0.5;} 
 
     100% {transform: translateY(0%);opacity: 1;} 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<header> 
 
<div class="container"> 
 
<div class="page_header"> 
 
<h1>Welcome to Animation Scroll</h1> 
 
</div> 
 
<div class="process"> 
 
<h2>Scroll down to change effect</h2> 
 
<a href="#">See our Process</a> 
 
<a href="#">View more</a> 
 
</div> 
 
</div> 
 
</header>

回答

2

您需要的文件绑定到$(document).scroll()。现在,您正在使用$(document).ready()事件,该事件仅声明文档准备就绪后应该发生的情况。但是为了在文档滚动时(事件)声明一组函数/特征,必须使用适当的jQuery事件,在本例中为scroll()

$(document).on("scroll", function() { 
    if ($(document).scrollTop() > 70) 
     { 
     $('.process h2').hide(); 
     $('.process a').show(); 

     } 
     else { 
      $('.process h2').show(); 
      $('.process a').hide(); 
     } 
}); 
+0

这就是我一直在寻找的,谢谢。但我有一个问题,先生,如果用户刷新页面上的设计垂直位置是50像素,效果是否仍然有效?原因我试过了,它仍然会显示文本不是按钮,除非用户将滚动一次,并且它会生效 –

+0

否。默认情况下,浏览器永远不会保存滚动位置。但是,您可以使用Cookie或本地存储来执行此操作,但不会引入全新的“复杂性”级别。但是,如果您有兴趣,请点击以下链接:https://stackoverflow.com/questions/29203312/how-can-i-retain-the-scroll-position-of-a-scrollable-area-when-pressing-回不过。如果它对你有帮助,不要忘记标记我的答案。谢谢! – Crashtor