检测哪个页面节在视口中 jQuery sectionInView

  • 源码大小:10.03KB
  • 所需积分:1积分
  • 源码编号:19JP-3275
  • 浏览次数:565次
  • 最后更新:2023年05月25日
  • 所属栏目:其他
本站默认解压密码:19jp.com 或 19jp_com

简介

sectionInView是一个很小的jQuery is in viewport插件,它可以检测页面的某个部分是在视口中可见还是隐藏在折叠下方。

如何使用它:

1.下载主脚本sectionInView.min.js并将其放在jQuery之后。

  1. <script src="/path/to/cdn/jquery.slim.min.js"></script>
  2. <script src="/path/to/sectionInView.min.js"></script>

2.初始化页面分区上的sectionInView插件,并做一些很酷的事情。在下面的示例中,您将看到位于视口中的页面部分的背景颜色将发生变化,同时将CSS类添加到相应的菜单项中。

  1. <nav>
  2. <a href="#section-1">Section One</a>
  3. <a href="#section-2">Section Two</a>
  4. <a href="#section-3">Section Three</a>
  5. </nav>
  6. <div class="container">
  7. <section id="section-1">
  8. <h2>Section One</h2>
  9. </section>
  10. <section id="section-2">
  11. <h2>Section Two</h2>
  12. </section>
  13. <section id="section-3">
  14. <h2>Section Three</h2>
  15. </section>
  16. </div>
  1. $("section").sectionInView(
  2. function (sectionId) {
  3. // is in the viewport
  4. $('section#' + sectionId +'').css("background-color", "yellow");
  5. $('a[href$="'+ sectionId +'"]').closest('li').addClass('active');
  6. },
  7. function (sectionId) {
  8. // is out of the viewport
  9. $('a[href$="'+ sectionId +'"]').closest('li').removeClass('active');
  10. },
  11. {
  12. offset: 200 // top offset in px
  13. }
  14. );

预览截图