累计签到:347 天 连续签到:7 天
|
基于JavaScript的网页返回顶部按钮实现
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Rocket Button</title>
- <style>
- #rocket {
- position: fixed;
- bottom: 50px;
- right: 50px;
- width: 50px;
- height: 50px;
- border: none;
- cursor: pointer;
- display: none;
- }
- /* 使用 SVG 图标 */
- #rocket .icon {
- width: 50px;
- height: 50px;
- transition: transform 0.3s ease;
- }
- @keyframes rocketLaunch {
- 0% {
- transform: translateY(0) scale(1);
- opacity: 1;
- }
- 100% {
- transform: translateY(-100vh) scale(0.5);
- opacity: 0;
- }
- }
- /* 添加悬停效果 */
- #rocket:hover .icon {
- transform: scale(1.1);
- }
- body {
- margin: 0;
- padding: 0;
- height: 200vh;
- background-color: #f0f0f0;
- }
- </style>
- </head>
- <body>
- <a class="back-to-top" id="rocket" aria-label="返回顶部">
- <!-- 使用 SVG 图标 -->
- <img class="icon" src="https://www.deepsook.cn/s/top.svg" alt="返回顶部">
- </a>
- <script>
- const rocket = document.getElementById('rocket');
- function debounce(func, wait) {
- let timeout;
- return function (...args) {
- clearTimeout(timeout);
- timeout = setTimeout(() => func.apply(this, args), wait);
- };
- }
- window.addEventListener('scroll', debounce(() => {
- if (document.body.scrollTop > 200 || document.documentElement.scrollTop > 200) {
- rocket.style.display = 'block';
- } else {
- rocket.style.display = 'none';
- }
- }, 100));
- rocket.addEventListener('click', () => {
- window.scrollTo({
- top: 0,
- behavior: 'smooth'
- });
- rocket.style.animation = 'rocketLaunch 1s cubic-bezier(0.215, 0.610, 0.355, 1) forwards';
-
- setTimeout(() => {
- rocket.style.animation = '';
- }, 1000);
- rocket.style.transform = 'scale(0.9)';
- setTimeout(() => {
- rocket.style.transform = 'scale(1)';
- }, 200);
- });
- </script>
- </body>
- </html>
复制代码
|
温馨提示:
1、在论坛里发表的文章仅代表作者本人的观点,与本网站立场无关。
2、论坛的所有内容都不保证其准确性,有效性,时间性。阅读本站内容因误导等因素而造成的损失本站不承担连带责任。
3、当政府机关依照法定程序要求披露信息时,论坛均得免责。
4、若因线路及非本站所能控制范围的故障导致暂停服务期间造成的一切不便与损失,论坛不负任何责任。
5、注册会员通过任何手段和方法针对论坛进行破坏,我们有权对其行为作出处理。并保留进一步追究其责任的权利。
6、如果有侵犯到您的权益,请第一时间联系邮箱 990037279@qq.com ,站长会进行审查,情况属实的会在三个工作日内为您删除。
|