2020-03-31 02:16:08 +08:00
|
|
|
(function () {
|
|
|
|
"use strict";
|
|
|
|
const smoothScrollLinks = document.getElementsByClassName("smooth-scroll");
|
2020-03-24 11:20:28 +08:00
|
|
|
|
|
|
|
const easeInOutQuad = function (t) {
|
2020-03-31 02:16:08 +08:00
|
|
|
return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
|
|
|
|
};
|
2020-03-24 11:20:28 +08:00
|
|
|
|
2020-03-31 02:16:08 +08:00
|
|
|
const scrollToEl = (
|
|
|
|
startTime,
|
|
|
|
currentTime,
|
|
|
|
duration,
|
|
|
|
scrollEndElemTop,
|
|
|
|
startScrollOffset
|
|
|
|
) => {
|
|
|
|
const runtime = currentTime - startTime;
|
|
|
|
let progress = runtime / duration;
|
2020-03-24 11:20:28 +08:00
|
|
|
|
2020-03-31 02:16:08 +08:00
|
|
|
progress = Math.min(progress, 1);
|
2020-03-24 11:20:28 +08:00
|
|
|
|
2020-03-31 02:16:08 +08:00
|
|
|
const ease = easeInOutQuad(progress);
|
2020-03-24 11:20:28 +08:00
|
|
|
|
2020-03-31 02:16:08 +08:00
|
|
|
window.scroll(0, startScrollOffset + scrollEndElemTop * ease);
|
2020-03-24 11:20:28 +08:00
|
|
|
if (runtime < duration) {
|
|
|
|
window.requestAnimationFrame((timestamp) => {
|
2020-03-31 02:16:08 +08:00
|
|
|
const currentTime = timestamp || new Date().getTime();
|
|
|
|
scrollToEl(
|
|
|
|
startTime,
|
|
|
|
currentTime,
|
|
|
|
duration,
|
|
|
|
scrollEndElemTop,
|
|
|
|
startScrollOffset
|
|
|
|
);
|
|
|
|
});
|
2020-03-24 11:20:28 +08:00
|
|
|
}
|
2020-03-31 02:16:08 +08:00
|
|
|
};
|
2020-03-24 11:20:28 +08:00
|
|
|
|
|
|
|
if (smoothScrollLinks.length > 0) {
|
|
|
|
for (let i = 0; i < smoothScrollLinks.length; i++) {
|
2020-03-31 02:16:08 +08:00
|
|
|
const smoothScrollLink = smoothScrollLinks[i];
|
2020-03-24 11:20:28 +08:00
|
|
|
|
2020-03-31 02:16:08 +08:00
|
|
|
smoothScrollLink.addEventListener("click", function (e) {
|
|
|
|
e.preventDefault();
|
|
|
|
const link = e.target.closest(".smooth-scroll");
|
|
|
|
const targetId = link.href.split("#")[1];
|
|
|
|
const target = document.getElementById(targetId);
|
|
|
|
const duration = link.getAttribute("data-duration") || 1000;
|
2020-03-24 11:20:28 +08:00
|
|
|
|
2020-03-31 02:16:08 +08:00
|
|
|
if (!target) return;
|
2020-03-24 11:20:28 +08:00
|
|
|
|
|
|
|
window.requestAnimationFrame((timestamp) => {
|
2020-03-31 02:16:08 +08:00
|
|
|
const stamp = timestamp || new Date().getTime();
|
|
|
|
const start = stamp;
|
2020-03-24 11:20:28 +08:00
|
|
|
|
2020-03-31 02:16:08 +08:00
|
|
|
const startScrollOffset = window.pageYOffset;
|
|
|
|
const scrollEndElemTop = target.getBoundingClientRect().top;
|
2020-03-24 11:20:28 +08:00
|
|
|
|
2020-03-31 02:16:08 +08:00
|
|
|
scrollToEl(
|
|
|
|
start,
|
|
|
|
stamp,
|
|
|
|
duration,
|
|
|
|
scrollEndElemTop,
|
|
|
|
startScrollOffset
|
|
|
|
);
|
|
|
|
});
|
|
|
|
});
|
2020-03-24 11:20:28 +08:00
|
|
|
}
|
|
|
|
}
|
2020-03-31 02:16:08 +08:00
|
|
|
})();
|