Wikipedia Smooth Scroll

Adds smooth scrolling for in-page links on Wikipedia and sister sites

当前为 2025-03-26 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Wikipedia Smooth Scroll
  3. // @description Adds smooth scrolling for in-page links on Wikipedia and sister sites
  4. // @version 0.1
  5. // @author Daniel Bronshtein
  6. // @grant none
  7. // @run-at document-idle
  8. // @match https://*.wikipedia.org/wiki/*
  9. // @match https://*.wiktionary.org/wiki/*
  10. // @match https://*.wikibooks.org/wiki/*
  11. // @match https://*.wikiquote.org/wiki/*
  12. // @match https://*.wikivoyage.org/wiki/*
  13. // @match https://*.wikisource.org/wiki/*
  14. // @match https://*.wikinews.org/wiki/*
  15. // @match https://*.wikiversity.org/wiki/*
  16. // @match https://*.wikifunctions.org/wiki/*
  17. // @namespace https://greasyfork.org/users/1450663
  18. // ==/UserScript==
  19. (function(){
  20. function scrollSmoothlyTo(element) {
  21. element.scrollIntoView({
  22. behavior: 'smooth'
  23. })
  24. }
  25. function getIdFromInternalLink(link) {
  26. try {
  27. return decodeURIComponent(link.getAttribute('href').substring(1))
  28. } catch (e) {
  29. return link.getAttribute('href').substring(1)
  30. }
  31. }
  32. function handleInternalLinkClick(event) {
  33. const link = event.currentTarget
  34. const id = getIdFromInternalLink(link)
  35. const element = document.getElementById(id)
  36. if (!element) return
  37. event.preventDefault()
  38. scrollSmoothlyTo(element)
  39. history.pushState({ scrollTo: id }, '', link.href)
  40. }
  41. document.querySelectorAll("a[href^='#']").forEach(link => {
  42. link.addEventListener('click', handleInternalLinkClick)
  43. })
  44. //ToDo: add smooth scrolling on popstate (when navigating back and forward)
  45. })()