利用jQuery实现当页面滚动超过一屏时显示返回顶部按钮
利用jQuery实现当页面滚动超过一屏时显示返回顶部按钮1、引入jquery.js,如下
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
2、写css,定位返回顶部图片的位置
<style>
#go_top {
position: fixed;
left: 95%;
bottom: 50px;
z-index: 99;
}
</style>
3、在界面引用返回顶部图片,位置可随意
<div id="go_top">
<img src="${basePath}image/return_top.gif" alt="回到顶部图片" title="回到顶部">
</div>
3、写对应的js,调用jquery的方法
<script type="text/javascript">
$(function () {
$("#go_top").hide();
})
//scroll() 方法为滚动事件
$(window).scroll(function(){
if ($(window).scrollTop()>100){
$("#go_top").fadeIn(800);
}else{
$("#go_top").fadeOut(800);
}
});
//返回顶部按钮点击
$("#go_top").click(function(){
$('body,html').animate({scrollTop:0},100);
return false;
});
</script>
4、如此,就实现了超过一屏出现返回顶部按钮,完整代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery实现超过一屏显示返回顶部按钮</title>
<style>
#go_top {
position: fixed;
left: 95%;
bottom: 50px;
z-index: 99;
}
</style>
</head>
<body>
<div id="go_top">
<img src="${basePath}image/return_top.gif" alt="回到顶部图片" title="回到顶部">
</div>
<div>
超长文章。。。占位。。。
</div>
<script src="${basePath}js/jquery-1.11.3.js"></script>
<script type="text/javascript">
$(function () {
$("#go_top").hide();
})
//scroll() 方法为滚动事件
$(window).scroll(function(){
if ($(window).scrollTop()>100){
$("#go_top").fadeIn(800);
}else{
$("#go_top").fadeOut(800);
}
});
//返回顶部按钮点击
$("#go_top").click(function(){
$('body,html').animate({scrollTop:0},100);
return false;
});
</script>
</body>
</html>