返回顶部(JQuery)

实现原理:

当滚动条的垂直偏移大于一定值时,正方形缓慢出现(height由0变为50px),反之,当其小于一定值时,正方形缓慢消失;

若点击正方形,则触发动画效果直到scrollTop为0,即到达页面顶部。

HTML

<a href="#header" id="backtop"></a>

CSS

#backtop{
  z-index: 999;
  position: fixed;
  bottom: 10px;
  right: 50px; 
  width: 50px; 
  height: 0;
  background-color: green;
  /* background: url(../images/backtop.png) center no-repeat; */
  transition: 1s;
}
#backtop.show {
   height: 50px;
}
/* html,body{height:auto;} */

JQuery

$(function(){
    $(window).scroll(function(){
      $(this).scrollTop()>10?$("#backtop").addClass('show'):$("#backtop").removeClass('show');
    })
    $("#backtop").click(function(){
      $("html,body").animate({scrollTop:0},700);
    })
})

猜你喜欢

转载自blog.csdn.net/Jane_3210/article/details/83247111