Skip to content

Instantly share code, notes, and snippets.

@forestlet
Last active February 25, 2022 03:46
Show Gist options
  • Save forestlet/d6596702fbe789a8cff02200acdbb900 to your computer and use it in GitHub Desktop.
Save forestlet/d6596702fbe789a8cff02200acdbb900 to your computer and use it in GitHub Desktop.
🔝 返回页面顶端 Back to Top
// ==UserScript==
// @name 返回顶端 BACK to TOP
// @description 为所有页面添加返回页面顶部的按钮
// @author forestlet
// @copyright 2022-
// @homepageURL
// @version 0.2
// @lastmodified 2022-02-25
// @namespace http://tampermonkey.net/
// @match http://*/*
// @include https://*/*
// @include file:///*
// @icon data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2280%22>🔝</text></svg>
// @grant none
// ==/UserScript==
(function () {
'use strict';
// Your code here...
let upupup = document.createElement('div')
upupup.id = "upupup"
upupup.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-caret-up" viewBox="0 0 16 16">
<path d="M3.204 11h9.592L8 5.519 3.204 11zm-.753-.659 4.796-5.48a1 1 0 0 1 1.506 0l4.796 5.48c.566.647.106 1.659-.753 1.659H3.204a1 1 0 0 1-.753-1.659z"/>
</svg>
`
upupup.style = `
position: fixed;
right: 20px;
bottom: 40px;
background-color: #fafafa;
border-radius: 50%;
width: 36px;
height: 36px;
line-height: 36px;
text-align: center;
display: none;
z-index: 9999;
box-shadow: 0 2px 6px 0 rgb(0 0 0 / 10%);
cursor: pointer;
`
upupup.addEventListener("click", () => {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
})
window.onscroll = () => {
if (document.body.scrollTop > 40 || document.documentElement.scrollTop > 40) {
document.getElementById("upupup").style.display = "block";
} else {
document.getElementById("upupup").style.display = "none";
}
}
let body = document.body || document.getElementsByTagName('body')[0];
body.appendChild(upupup);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment