CSS返回顶部的原理是,当点击某个按钮时,触发一个函数,通过改变页面的滚动位置来实现返回顶部的效果。以下是一个示例代码:
CSS返回顶部的原理是,当点击某个按钮时,触发一个JavaScript函数,通过改变页面的滚动位置来实现返回顶部的效果。
以下是一个示例代码:
HTML:
html
Back to top
CSS:
css
.back-to-top {
position: fixed;
bottom: 30px;
right: 30px;
}
JS:
javascript
// When the user scrolls down 20px from the top of the document, show the on
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("myBtn").style.display = "block";
} else {
document.getElementById("myBtn").style.display = "none";
}
}
// When the user clicks on the on, scroll to the top of the document
function topFunction() {
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}