scrollDetection是一个很小的jQuery插件,它可以检测滚动方向(上下)和滚动位置,并相应地将CSS类添加到特定的指示符元素中。
1.插入主脚本jquery.scroll-direction.js查询
加载jQuery库之后,我们就可以开始了。请注意,从v2.0开始,jQuery现在是可选的。
- <script src="/path/to/cdn/jquery.slim.min.js"></script>
- <script src="/path/to/jquery.scroll-direction.js"></script>
2.初始化插件以激活滚动方向和位置跟踪器。
- // jQuery
- $.scrollDirection.init({
- // options here
- })
- // Vanilla JS
- window.scrollDirection.init({
- // options here
- });
3.确定跟踪时是否考虑顶部和底部偏移。
- $.scrollDirection.init({
- // top offset in px
- topOffset: 0,
- // bottom offset in px
- bottomOffset: 0,
- // consider bottom as middle
- atBottomIsAtMiddle: true
- })
4.在滚动时将自定义CSS类添加到指示符元素(默认值:body)。
- $.scrollDirection.init({
- indicator: true,
- indicatorElement: $("body"),
- scrollUpClass: "scroll-up",
- scrollDownClass: "scroll-down",
- scrollAtTopClass: "scroll-top",
- scrollAtMiddleClass: "scroll-middle",
- scrollAtBottomClass: "scroll-bottom",
- })
5.当滚动经过一个额外的指示符元素时,将自定义CSS类添加到该元素。
- $.scrollDirection.init({
- extraIndicators: {
- "element": $("#extra-element"),
- "class": "custom-class",
- }
- })
6.将根据当前滚动方向和位置触发的可用事件。
- $(window).on("scrollDirection", function () {
- // on load, resize, or scroll
- });
- $(window).on("scrollUp", function () {
- // on scroll up
- });
- $(window).on("scrollDown", function () {
- // on scroll down
- });
- $(window).on("scrollAtTop", function () {
- // when reaching the top
- });
- $(window).on("scrollAtMiddle", function () {
- // when reaching the middle zone
- });
- $(window).on("scrollAtBottom", function () {
- // when reaching the bottom
- });
7.可用属性。
- if($.scrollDirection.isScrollUp){
- // is scrolling up
- }
- if($.scrollDirection.isScrollDown){
- // is scrolling down
- }
- if($.scrollDirection.isScrollAtTop){
- // is reaching the top
- }
- if($.scrollDirection.isScrollAtMiddle){
- // is reaching the middle zone
- }
- if($.scrollDirection.isScrollAtBottom){
- // is reaching the bottom
- }
v2.0.0版本(2022-02-15)