如题。
当网页比较长之后,我们需要在页面添加一个返回顶部的功能。这个功能我们实现的方法有很多,例如,可以使用window.scrollTo(0,100)来实现。
如果我要求实现的效果炫一些。
例如,当页面滑动到一定的距离之后再出现这个返回按钮,返回按钮出现与消失要有淡出淡入的效果,来吧,让我用下面这段函数做出这个效果吧:
js代码:
//返回顶部的按钮
$(document).ready(function(){
// 页面向下滚动超过300px时按钮显示,否则隐藏
$(window).scroll(function(){
if($(this).scrollTop()>300){
$('.back-to-top').fadeIn(700);//淡入
} else {
$('.back-to-top').fadeOut(700);//淡入
}
});
// 点击按钮,向上动画滚动
$('.back-to-top').click(function(event){
event.preventDefault();
//利用animate实现缓慢滑动回顶部的功能
$('html,body').animate({scrollTop:0},500);
})
}); html内容
返回顶部
css内容:
.back-to-top {
position: fixed;
bottom: 1em;
right: 9.5em;
background-color: #000;
opacity:0.8;
text-align: center;
padding: 10px 12px;
color: #eee;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
cursor: pointer;
display: none;
z-index:9000;
}
.back-to-top span{
font-size:14px;
font-family:"微软雅黑";
} 实现效果如demo给出的效果所示: