JS瀹炵幇鍥炲埌椤甸潰椤堕儴鐨勪簲绉嶅啓娉?浠庡疄鐜板埌澧炲己)
- 浣跨敤window.scrollTo鎴杁ocument.documentElement.scrollTop鏂规硶瀹炵幇锛?/li>
function scrollToTop() {
window.scrollTo(0, 0);
}
- 浣跨敤window.scrollTo鏂规硶缁撳悎requestAnimationFrame瀹炵幇骞虫粦婊氬姩鏁堟灉锛?/li>
function smoothScrollToTop() {
const currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
if (currentScroll > 0) {
window.requestAnimationFrame(smoothScrollToTop);
window.scrollTo(0, currentScroll - (currentScroll / 8));
}
}
- 浣跨敤scrollIntoView鏂规硶瀹炵幇婊氬姩鍒版寚瀹氬厓绱犵殑椤堕儴锛?/li>
function scrollToElementTop(element) {
element.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
- 浣跨敤animate鏂规硶瀹炵幇骞虫粦婊氬姩鏁堟灉锛?/li>
function animateScrollToTop(duration) {
const start = document.documentElement.scrollTop || document.body.scrollTop;
const target = 0;
const distance = target - start;
const startTime = performance.now();
function step() {
const currentTime = performance.now();
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
const easing = function(t) { return t * (2 - t); }; // 缂撳姩鍑芥暟锛屼緥濡備娇鐢ㄤ簩娆℃柟鍑芥暟
const position = start + distance * easing(progress);
window.scrollTo(0, position);
if (progress < 1) {
window.requestAnimationFrame(step);
}
}
window.requestAnimationFrame(step);
}
- 澧炲己鐗堟湰锛氭坊鍔犳寜閽厓绱狅紝骞剁粦瀹氱偣鍑讳簨浠讹細
<button id="scrollToTopBtn">鍥炲埌椤堕儴</button>
document.getElementById('scrollToTopBtn').addEventListener('click', scrollToTop);
function scrollToTop() {
window.scrollTo({ top: 0, behavior: 'smooth' });
}
浠ヤ笂鏄簲绉嶅父瑙佺殑鍥炲埌椤甸潰椤堕儴鐨勫疄鐜版柟娉曪紝浠庢渶鍩烘湰鐨勬粴鍔ㄥ埌椤堕儴鍒板寮虹増甯︽湁骞虫粦婊氬姩鏁堟灉鍜屾寜閽偣鍑讳簨浠剁殑鍐欐硶銆傚彲浠ユ牴鎹叿浣撻渶姹傞€夋嫨鐩稿簲鐨勬柟娉曟潵瀹炵幇鍥炲埌椤甸潰椤堕儴鐨勫姛鑳姐€?/p>