sectionInView是一个很小的jQuery is in viewport插件,它可以检测页面的某个部分是在视口中可见还是隐藏在折叠下方。
1.下载主脚本sectionInView.min.js并将其放在jQuery之后。
- <script src="/path/to/cdn/jquery.slim.min.js"></script>
- <script src="/path/to/sectionInView.min.js"></script>
2.初始化页面分区上的sectionInView插件,并做一些很酷的事情。在下面的示例中,您将看到位于视口中的页面部分的背景颜色将发生变化,同时将CSS类添加到相应的菜单项中。
- <nav>
- <a href="#section-1">Section One</a>
- <a href="#section-2">Section Two</a>
- <a href="#section-3">Section Three</a>
- </nav>
- <div class="container">
- <section id="section-1">
- <h2>Section One</h2>
- </section>
- <section id="section-2">
- <h2>Section Two</h2>
- </section>
- <section id="section-3">
- <h2>Section Three</h2>
- </section>
- </div>
- $("section").sectionInView(
- function (sectionId) {
- // is in the viewport
- $('section#' + sectionId +'').css("background-color", "yellow");
- $('a[href$="'+ sectionId +'"]').closest('li').addClass('active');
- },
- function (sectionId) {
- // is out of the viewport
- $('a[href$="'+ sectionId +'"]').closest('li').removeClass('active');
- },
- {
- offset: 200 // top offset in px
- }
- );