如何使内容出现在向下滚动网页时?

新手上路,请多包涵

当我向下滚动网页时,我看到了内容出现的网站。我有这段代码,但它不起作用。你能指导并给予适当的解释吗?

 $(document).ready(function(){
  //Take your div into one js variable
  var div = $("#divToShowHide");
  //Take the current position (vertical position from top) of your div in the variable
  var pos = div.position();
  //Now when scroll event trigger do following
  $(window).scroll(function () {
   var windowpos = $(window).scrollTop();
   //Now if you scroll more than 100 pixels vertically change the class to AfterScroll
   // I am taking 100px scroll, you can take whatever you need
   if (windowpos >= (pos.top-100)) {
     div.addClass("AfterScroll");
   }
   //If scroll is less than 100px, remove the class AfterScroll so that your content will be hidden again
   else {
     div.removeClass("AfterScroll");
   }
   //Note: If you want the content should be shown always once you scroll and do not want to hide it again when go to top agian, no need to write the else part
 });
});
 .BeforeScroll
{
  height: 100px; /*Whatever you want*/
  width: 100%; /*Whatever you want*/
  display: none;
}

/*Use this class when you want your content to be shown after some scroll*/
.AfterScroll
{
  height: 100px; /*Whatever you want*/
  width: 100%; /*Whatever you want*/
  display: block;
}
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "divToShowHide" class = "BeforeScroll">Content you want to show hide on scroll
 </div>

原文由 Varun Jain 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 368
2 个回答

如果你也想制作一些动画,我会建议你 AOS

这是一个 Animate On Scroll Library,你可以让内容在向下滚动时出现


如何使用:

在 HTML 标签中添加“data-aos=“animation name”” 就可以了:

 <div class="topBar" data-aos="fade-in">

添加后:

 <link href="https://cdn.rawgit.com/michalsnik/aos/2.1.1/dist/aos.css" rel="stylesheet">

在头部并添加:

 <script src="https://cdn.rawgit.com/michalsnik/aos/2.1.1/dist/aos.js"></script>

在 body 标签结束之前。

一个简单的例子: https ://codepen.io/karenmio/pen/KxGewG

您可以从中学到一些变化,但相关网站确实会尝试向您出售课程,如果此链接不正确,请告诉我/或将其删除:https: //codepen.io/SitePoint/pen/MmxQMG

原文由 id3vz 发布,翻译遵循 CC BY-SA 4.0 许可协议

我将举一个 scrollrevealjs 的例子

像这样包含库:

 <script src="https://cdn.jsdelivr.net/scrollreveal.js/3.3.1/scrollreveal.min.js"></script>

然后在你的js文件中初始化库

window.sr = ScrollReveal();

然后只需添加您想要设置动画的组件的类

sr.reveal('.YourClass1');
sr.reveal('.YourClass2');

在这里你会找到如何使用这个库:)

https://github.com/jlmakes/scrollreveal.js

原文由 Asen Sokolov 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题