3步实现网页一键回到顶部功能

Step 1.修改 footer


app/views/common/_footer.html.erb
<a href="#myPage" >
    <span id="gotop">回到<br/>顶部></span>
 </a>

Step 2. 添加样式



app/assets/stylesheets/application.scss

//回到顶部
#gotop {
  width: 50px;
  height: 50px;
  position: fixed;
  right: 20px;
  bottom: 20px;
  background-color: rgb(25,187,49);//
  color: #ffffff;
  border-radius: 50%;
  padding: 5px 9px;
  cursor: pointer;
  display: none; /*默认先隐藏掉*/
}

Step 3. 添加JS



app/assets/javascripts/application.js

//顶部回到

$(document).on('click', '#gotop', function () {

  $('body').animate({'scrollTop': 0}, 500) //在500ms的时间内,慢慢地回到顶部

})

 $(window).scroll(function () {
   if ($(this).scrollTop() > 560) {
     $('#gotop').fadeIn() // 当页面向下滚动的距离大于500px时,慢慢地显示「回到顶部按钮」
   } else {
     $('#gotop').fadeOut() // 否则慢慢地隐藏「回到顶部按钮」
   }
 })

大功告成!!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容