预览
HTML
<button class="backtotop" onclick="scrollToTop()">
<span class="sr-only">返回顶部</span>
</button>
注意这个sr-only的类是Font Awesome的css,如果你没有引用Font Awesome的css,就加一行代码
.sr-only{text-indent: -9999px;overflow: hidden;}
CSS
.backtotop{position:fixed;bottom:20px;right:20px;width:64px;height:64px;border:none;border-radius:50%;background-color:#33333330;color:#fff;font-size:20px;line-height:64px;text-align:center;cursor:pointer;transition:background-color.3s,transform.3s;z-index:10}.backtotop{background:url('data:image/svg+xml;base64,PHN2ZyB0PSIxNzEwNzAyMTAwOTkyIiBjbGFzcz0iaWNvbiIgdmlld0JveD0iMCAwIDEwMjQgMTAyNCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHAtaWQ9Ijc5MzgiPjxwYXRoIGQ9Ik0wIDUxMkMwIDIyOS4yMjI0IDIyOS4yMjI0IDAgNTEyIDBzNTEyIDIyOS4yMjI0IDUxMiA1MTItMjI5LjIyMjQgNTEyLTUxMiA1MTJTMCA3OTQuNzc3NiAwIDUxMnoiIGZpbGw9IiMyRDZDRkMiIHAtaWQ9Ijc5MzkiPjwvcGF0aD48cGF0aCBkPSJNNjU2LjQzNTIgNDYzLjQzNjhjMi42NjI0LTE3NC4yODQ4LTEzOS4zOTItMjUzLjI2MDgtMTQ4LjkxNTItMjU4LjM4MDhWMjA0LjhsLTAuMjU2IDAuMTI4LTAuMjU2LTAuMTI4djAuMjU2Yy05LjU3NDQgNS4xMi0xNTEuNjI4OCA4NC4wOTYtMTQ4Ljk2NjQgMjU4LjM4MDgtMjguOTI4IDE4Ljg2NzItNTkuMjM4NCA1Mi40Mjg4LTU0LjQgMTEwLjQzODQgNC44MTI4IDU4LjAwOTYgNjAuNTk1MiA5Ni40NjA4IDgxLjk0NTYgOTQuMzg3MiAyMS4zNzYtMi4wOTkyIDE1LjE1NTItMTguMTc2IDE1LjE1NTItMTguMTc2bDcuMzIxNi0zMC4wOHMzMS40ODggNDguMz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DggNy4wOTEyIDAgMTIuODUxMiA1LjgzNjggMTIuODUxMiAxMy4wMDQ4djk0LjI1OTJ6IG00Mi42NzUyLTQ5LjIwMzJjMCA3LjA2NTYtNS42MzIgMTIuOC0xMi42MjA4IDEyLjhhMTIuNzQ4OCAxMi43NDg4IDAgMCAxLTEyLjYyMDgtMTIuOHYtNDUuMjM1MmMwLTcuMDQgNS42MzItMTIuNzc0NCAxMi42MjA4LTEyLjc3NDQgNi45NjMyIDAgMTIuNjIwOCA1LjczNDQgMTIuNjIwOCAxMi44djQ1LjIwOTZ6IiBmaWxsPSIjRkZGRkZGIiBwLWlkPSI3OTQwIj48L3BhdGg+PC9zdmc+')center center no-repeat;background-size:48px}.backtotop:hover{background-color:#33333330}.dark.backtotop:hover{background-color:#ccae2a1a}.backtotop svg{width:48px;height:48px;fill:#fff}
Javascript
<script type="text/javascript">
// 获取返回顶部按钮元素
var backToTopButton = document.querySelector('.backtotop');
// 当用户滚动时,检查页面滚动距离是否超过100像素
window.addEventListener('scroll', function() {
if (window.pageYOffset > 100) {
// 如果滚动距离大于100像素,显示返回顶部按钮
backToTopButton.style.display = 'block';
} else {
// 如果滚动距离小于等于100像素,隐藏返回顶部按钮
backToTopButton.style.display = 'none';
}
});
// 点击返回顶部按钮时,平滑滚动到页面顶部
function scrollToTop() {
var scrollDuration = 800; // 滚动到顶部的持续时间(毫秒)
var scrollStep = -window.scrollY / (scrollDuration / 15);
function scrollAnimation(currentTime) {
var currentTime = currentTime || 0;
var scrollInterval = 15; // 每次滚动的时间间隔(毫秒)
var newScrollPosition = window.scrollY + scrollStep * scrollInterval;
if (newScrollPosition <= 0) {
window.scrollTo(0, 0);
return;
}
window.scrollTo(0, newScrollPosition);
requestAnimationFrame(function(timestamp) {
scrollAnimation(timestamp);
});
}
requestAnimationFrame(function(timestamp) {
scrollAnimation(timestamp);
});
}
</script>
最后于 3月前
被juse编辑
,原因: