检查元素相对于视口 位置 jQuery ExopitInViewPort

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

简介

还有另一个jQuery支持的Is In Viewport插件,可用于在向下/向上滚动页面时检查元素相对于视口的当前位置。

它提供了一组有用的回调,当目标元素进入或离开视口时,当整个元素在视口内时,或当元素的一部分在视口内/外时,将触发这些回调。

非常适合图像延迟加载、滚动触发动画、无限滚动、视差效果、滚动位置指示器、DOM可见性切换等。

如何使用它:

1.在您的jQuery项目中下载并导入ExopitInViewPort插件。

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

2.选择要跟踪的元素,然后调用.exopiteInViewPort()方法:

  1. $('.element').exopiteInViewPort({
  2.  
  3. // enter the viewport
  4. // direction = top, bottom
  5. onEnter: function(element, direction) {
  6. if ( direction == 'top' ) {
  7. alert('Element entered from top');
  8. } else if ( direction == 'bottom' ) {
  9. alert('Element entered from bottom');
  10. }
  11. },
  12.  
  13. // outside the viewport
  14. // direction = top, bottom
  15. onLeft: function(element, direction) {
  16. alert('Element left ' + direction);
  17. },
  18.  
  19. // return true if the whole element is in viewport
  20. onWholeInside: function(element, inViewport) {
  21. if (inViewport) {
  22. alert('The whole element is inside the viewport');
  23. } else {
  24. alert('Not the whole element is inside the viewport');
  25. }
  26. },
  27.  
  28. });

3.此插件提供了掐死减少检查频率的选项,这有助于显著提高网站的性能。默认值:100。

  1. $('.element').exopiteInViewPort({
  2. throttle: 200,
  3. });

4.设置元素的偏移和填充。当你在页面上有一个粘性的页眉/页脚导航时,这会很有帮助。

  1. $('.element').exopiteInViewPort({
  2. offset: 0,
  3. paddingTop: 0,
  4. paddingBottom: 0,
  5. });

预览截图