平滑滚动到页面上 任何位置 jQuery平滑滚动

  • 源码大小:19.97KB
  • 所需积分:1积分
  • 源码编号:19JP-3774
  • 浏览次数:300次
  • 最后更新:2023年07月21日
  • 所属栏目:动画
本站默认解压密码:19jp.com 或 19jp_com

简介

一个小巧的jQuery平滑滚动插件,允许您将页面垂直平滑地滚动到文档的任何位置。

这个插件最棒的地方是,它允许您将平滑滚动行为绑定到任何事件,如触摸点击和鼠标点击,而不仅仅是锚链接。

参见:

  • 10个最佳平滑滚动JavaScript/jQuery插件

如何使用它:

1.加载主脚本平滑滚动.js在jQuery之后。

<script src="/path/to/cdn/jquery.slim.min.js"></script>
<script src="/path/to/SmoothScrolling.js"></script>

2.将页面滚动到特定位置:

smoothScrolling.scrollToTargetY(targetYInPixels);

3.将平滑滚动行为绑定到任何事件,如下所示:

// for Safari
let allowScrolling = true; 

$(window).on("touchmove", function(e) {
  // for Safari
  allowScrolling = false; 
});

$(window).on("click touchend", function(e) {
  if (e.target.tagName != "A" && allowScrolling) { 
    // for Safari
    event.stopPropagation();
    event.preventDefault();

    const maxHeight = $(document).height();
    const randomPercentage = Math.random();
    const randomHeight = randomPercentage * maxHeight;

    smoothScrolling.scrollToTargetY(randomHeight);
  }
  else
    // for Safari
    allowScrolling = true; 
});

预览截图