MediaWiki:Gadget-Backtotop.js:修订间差异
来自康健生活
创建页面,内容为“// <pre> →回到顶部: $(function() { var body = document.body, html = document.documentElement; var innerWidth = window.innerWidth; var scr…” |
无编辑摘要 |
||
| (未显示同一用户的1个中间版本) | |||
| 第1行: | 第1行: | ||
(function () { | |||
'use strict'; | |||
var topButton; | |||
var bottomButton; | |||
var scrollThreshold = 240; | |||
function updateButtonVisibility() { | |||
topButton.hidden = window.scrollY < scrollThreshold; | |||
bottomButton.hidden = window.scrollY + window.innerHeight >= | |||
document.documentElement.scrollHeight - 1; | |||
} | |||
function scrollToPageEdge(edge) { | |||
var prefersReducedMotion = window.matchMedia && | |||
window.matchMedia('(prefers-reduced-motion: reduce)').matches; | |||
var top = edge === 'top' ? 0 : document.documentElement.scrollHeight; | |||
window.scrollTo({ | |||
top: top, | |||
behavior: prefersReducedMotion ? 'instant' : 'smooth' | |||
}); | |||
} | |||
function createButton(label, ariaLabel, edge) { | |||
var button = document.createElement('button'); | |||
button.className = 'page-scroll-button'; | |||
button.type = 'button'; | |||
button.textContent = label; | |||
button.setAttribute('aria-label', ariaLabel); | |||
button.addEventListener('click', function () { | |||
scrollToPageEdge(edge); | |||
}); | |||
return button; | |||
} | |||
function initializeBackToTop() { | |||
if (topButton) { | |||
return; | |||
} | |||
}); | var controls = document.createElement('div'); | ||
controls.className = 'page-scroll-controls'; | |||
topButton = createButton('⬆', '返回页面顶部', 'top'); | |||
bottomButton = createButton('⬇', '转到页面底部', 'bottom'); | |||
controls.appendChild(topButton); | |||
controls.appendChild(bottomButton); | |||
document.body.appendChild(controls); | |||
window.addEventListener('scroll', updateButtonVisibility, { passive: true }); | |||
updateButtonVisibility(); | |||
} | |||
if (document.readyState === 'loading') { | |||
document.addEventListener('DOMContentLoaded', initializeBackToTop, { once: true }); | |||
} else { | |||
initializeBackToTop(); | |||
} | |||
})(); | |||