制作滚动顶部/底部按钮的最佳方式



所以我在我的html页面的右下角做了一个按钮,但我想知道,因为这是我第一次做这个,如果有另一种更好的方法来做到这一点,或者如果你们能看到什么关于我这样做的奇怪的方式?

这篇文章主要是为了学习如何以正确的方式做事,因为我是一个初学者。

谢谢你的帮助。

这是我的代码——比;如果你想GOTO: JSfiddle

var bottomPage = document.getElementById('bottomPage');
var topPage = document.getElementById('topPage');
var lastScrollTop = 0;
bottomPage.addEventListener('click', scrollBottom);
topPage.addEventListener('click', scrollTop);
// element should be replaced with the actual target element on which you have applied scroll, use window in case of no target element.
window.addEventListener('scroll', function(){ // or element.addEventListener('scroll'....
var st = window.pageYOffset || document.documentElement.scrollTop;
if (st > lastScrollTop){
bottomPage.style.display = 'none';
topPage.style.display = '';
} else {
bottomPage.style.display = '';
topPage.style.display = 'none';
}
lastScrollTop = st <= 0 ? 0 : st;
}, false);
function scrollBottom() {
window.scrollTo(0,document.body.scrollHeight);
bottomPage.style.display = 'none';
topPage.style.display = '';
}
function scrollTop() {
window.scrollTo(0, 0);
topPage.style.display = 'none';
bottomPage.style.display = '';
}
body{
height: 3000px;
background: white;
background: linear-gradient(to bottom, #33ccff 0%, #ff99cc 100%);
}
.right-corder-container {
position: fixed;
right: 20px;
bottom: 20px;
vertical-align: middle;
background: #dddddd79;
text-align: center;
width: 40px;
height: 40px;
border-radius: 100%;
display: inline-flex;
flex-direction: column;
justify-content: center;
align-items: center;
font-size: 25px;
color: white;
font-weight: bold;
text-decoration: none
}
.right-corder-container img {
width: 40px;
height: 40px;
}
.right-corder-container:hover {
background: #85858579;
cursor: pointer;
}
<body>
<button class='right-corder-container' id='bottomPage' type='button'><img src='https://i.postimg.cc/87f0hmm2/scroll-down.png'></button>
<button class='right-corder-container' style='display: none;' id='topPage' type='button'><img src='https://i.postimg.cc/Tp4sL4gj/scroll-up.png'></button>

</body>

您可以做如下操作。我使用jQuery使代码更简单。另外,在CSS中添加了html {scroll-behavior: smooth},以创建平滑的滚动。

$('.btn').on('click', function(){
let btn = $(this)
setTimeout(function(){
if(btn.text() == 'GO down'){
btn.text('GO up');
btn.attr('href','#top');
}else{
btn.text('GO down')
btn.attr('href','#bottom')
}
}, 600);
});
html{scroll-behavior: smooth}
.main{height:2000px;background:#f7f7f7}
.btn{position:fixed;right:50px;bottom:50px}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="top"></div>
<a class="btn" href="#bottom">GO down</a>
<div class="main"></div>
<div id="bottom"></div>

我使用setTimeout()方法对文本和属性href的更改进行延迟,因此当页面停止滚动时,它会产生更改的效果。

最新更新