返回顶部按钮能够帮助用户快速平滑的返回到页面的顶部。
HTML结构
在body标签结束之前添加返回顶部按钮:
<body> <!-- all your content here --> <a href="#0" class="cd-top">Top</a> <!-- link to scripts here --> </body>
CSS样式
返回顶部按钮始终出现在页面的右边。初始化时它是不可见的:visibility:hidden; 和 opacity:0;。这两个属性可以通过2个class来控制:.cd-is-visible 和.cd-fade-out。
.cd-top.cd-is-visible { /* the button becomes visible */ visibility: visible; opacity: 1; } .cd-top.cd-fade-out { /* if the user keeps scrolling down, the button is out of focus and becomes less visible */ opacity: .5; }
JAVASCRIPT
在demo中,我们使用三个变量来控制返回顶部按钮:
//browser window scroll (in pixels) after which the "back to top" link is shown var offset = 300, //browser window scroll (in pixels) after which the "back to top" link opacity is reduced offset_opacity = 1200, //duration of the top scrolling animation (in ms) scroll_top_duration = 700;
offset变量用于切换.cd-is-visible类。offset_opacity用于控制.cd-fade-out。
返回顶部的动画使用的是jQuery .animate()方法。