在jQuery中检测滚动方向和位置

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

简介

scrollDetection是一个很小的jQuery插件,它可以检测滚动方向(上下)和滚动位置,并相应地将CSS类添加到特定的指示符元素中。

参见:

  • 使用jQuery实现最小滚动方向检测-滚动检测
  • 使用jQuery检测滚动方向-滚动方向

如何使用它:

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)

  • 添加jQuery免费功能。
  • 添加缩小版

预览截图