还有另一个jQuery支持的Is In Viewport插件,可用于在向下/向上滚动页面时检查元素相对于视口的当前位置。
它提供了一组有用的回调,当目标元素进入或离开视口时,当整个元素在视口内时,或当元素的一部分在视口内/外时,将触发这些回调。
非常适合图像延迟加载、滚动触发动画、无限滚动、视差效果、滚动位置指示器、DOM可见性切换等。
1.在您的jQuery项目中下载并导入ExopitInViewPort插件。
- <script src="/path/to/cdn/jquery.slim.min.js"></script>
- <script src="/path/to/jquery.exopiteinviewport.js"></script>
2.选择要跟踪的元素,然后调用.exopiteInViewPort()
方法:
- $('.element').exopiteInViewPort({
- // enter the viewport
- // direction = top, bottom
- onEnter: function(element, direction) {
- if ( direction == 'top' ) {
- alert('Element entered from top');
- } else if ( direction == 'bottom' ) {
- alert('Element entered from bottom');
- }
- },
- // outside the viewport
- // direction = top, bottom
- onLeft: function(element, direction) {
- alert('Element left ' + direction);
- },
- // return true if the whole element is in viewport
- onWholeInside: function(element, inViewport) {
- if (inViewport) {
- alert('The whole element is inside the viewport');
- } else {
- alert('Not the whole element is inside the viewport');
- }
- },
- });
3.此插件提供了掐死
减少检查频率的选项,这有助于显著提高网站的性能。默认值:100。
- $('.element').exopiteInViewPort({
- throttle: 200,
- });
4.设置元素的偏移和填充。当你在页面上有一个粘性的页眉/页脚导航时,这会很有帮助。
- $('.element').exopiteInViewPort({
- offset: 0,
- paddingTop: 0,
- paddingBottom: 0,
- });