xavieryang revised this gist . Go to revision
1 file changed, 1 insertion, 1 deletion
scroll_to_top.js
@@ -1,6 +1,6 @@ | |||
1 | 1 | // 创建按钮 | |
2 | 2 | const backToTopBtn = document.createElement('button'); | |
3 | - | backToTopBtn.innerText = '↑ Top'; | |
3 | + | backToTopBtn.innerText = '↑'; | |
4 | 4 | backToTopBtn.style.position = 'fixed'; | |
5 | 5 | backToTopBtn.style.bottom = '20px'; | |
6 | 6 | backToTopBtn.style.right = '20px'; |
xavieryang revised this gist . Go to revision
1 file changed, 32 insertions
scroll_to_top.js(file created)
@@ -0,0 +1,32 @@ | |||
1 | + | // 创建按钮 | |
2 | + | const backToTopBtn = document.createElement('button'); | |
3 | + | backToTopBtn.innerText = '↑ Top'; | |
4 | + | backToTopBtn.style.position = 'fixed'; | |
5 | + | backToTopBtn.style.bottom = '20px'; | |
6 | + | backToTopBtn.style.right = '20px'; | |
7 | + | backToTopBtn.style.padding = '10px 15px'; | |
8 | + | backToTopBtn.style.backgroundColor = '#007bff'; | |
9 | + | backToTopBtn.style.color = 'white'; | |
10 | + | backToTopBtn.style.border = 'none'; | |
11 | + | backToTopBtn.style.borderRadius = '5px'; | |
12 | + | backToTopBtn.style.cursor = 'pointer'; | |
13 | + | backToTopBtn.style.boxShadow = '0 4px 6px rgba(0, 0, 0, 0.1)'; | |
14 | + | backToTopBtn.style.zIndex = '1000'; | |
15 | + | backToTopBtn.style.display = 'none'; // 默认隐藏 | |
16 | + | ||
17 | + | // 按钮平滑滚动到顶部 | |
18 | + | backToTopBtn.addEventListener('click', () => { | |
19 | + | window.scrollTo({ top: 0, behavior: 'smooth' }); | |
20 | + | }); | |
21 | + | ||
22 | + | // 添加按钮到页面 | |
23 | + | document.body.appendChild(backToTopBtn); | |
24 | + | ||
25 | + | // 监听滚动事件,显示/隐藏按钮 | |
26 | + | window.addEventListener('scroll', () => { | |
27 | + | if (window.scrollY > 300) { // 当滚动超过 300px 时显示按钮 | |
28 | + | backToTopBtn.style.display = 'block'; | |
29 | + | } else { | |
30 | + | backToTopBtn.style.display = 'none'; | |
31 | + | } | |
32 | + | }); |