JavaScript平滑返回指定ID元素的顶部代码
以下是使用JavaScript实现平滑返回指定ID元素的顶部的代码:
function smoothScrollToTop(elementId) {
const element = document.getElementById(elementId);
const offset = element.getBoundingClientRect().top;
const duration = 500; // 滚动持续时间
const startingY = window.pageYOffset;
const diff = Math.abs(offset);
let start;
// 滚动函数
function step(timestamp) {
if (!start) start = timestamp;
const time = timestamp - start;
const percent = Math.min(time / duration, 1);
window.scrollTo(0, startingY - (offset * percent));
if (time < duration) {
window.requestAnimationFrame(step);
}
}
// 开始滚动
window.requestAnimationFrame(step);
}
使用方法:
smoothScrollToTop('myElementId');
其中,myElementId是要滚动到顶部的元素的ID。duration控制滚动的持续时间,单位为毫秒。可以根据需要调整。
原文地址: https://www.cveoy.top/t/topic/6Rc 著作权归作者所有。请勿转载和采集!