返回顶部按钮效果js实现

HTML代码:

返回顶部

CSS代码:

.back-to-top {
  display: none; /* 默认隐藏按钮 */
  position: fixed; /* 固定位置 */
  bottom: 20px;
  right: 20px;
  width: 80px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  background-color: #ccc;
  border-radius: 20px;
  color: #fff;
  font-size: 16px;
}

.back-to-top:hover {
  background-color: #999; /* 鼠标移入时变色 */
}

JS代码:

window.onscroll = function() {
  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  // 根据滚动位置是否大于一定值来控制按钮的显示与隐藏
  if(scrollTop > 100) {
    document.querySelector('.back-to-top').style.display = 'block';
  } else {
    document.querySelector('.back-to-top').style.display = 'none';
  }
}

document.querySelector('.back-to-top').onclick = function() {
  // 点击按钮时回到顶部
  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  var speed = Math.floor(scrollTop / 20);
  var timer = setInterval(function(){
    if(scrollTop > 0){
      document.documentElement.scrollTop = document.body.scrollTop = scrollTop - speed;
      scrollTop = scrollTop - speed;
    }
    else {
      clearInterval(timer);
    }
  }, 20);
}

你可能感兴趣的:(HTML,CSS,JS和jQ的前端开发应用,javascript,css,前端)