您的位置:首页 > 其它

回顶部特效

2016-12-19 20:50 183 查看
1.类似淘宝等网站的回顶部特效,用jquery实现,当页面内容滚动距离页面顶部300的时候,出现回顶部按钮,点击后平滑地回到顶部,代码如下:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.top{
width: 50px;
height: 50px;
display: block;
background: #888;
color: #fff;
text-align: center;
line-height: 50px;
font-size: 30px;
text-decoration: none;
position: fixed;
right: 50px;
bottom:50px;
display: none;
}
.top:hover{background: #093}
</style>
<script src="jquery-1.11.0.min.js"></script>
<script>
$(function(){
$(window).scroll(function(){
var t=$(this).scrollTop();
if(t>300){
$(".top").stop().fadeIn(300);
}else{
$(".top").stop().fadeOut(300);
}
});
$(".top").click(function(){
$("body,html").stop().animate({scrollTop:0},300); //html是为了兼容火狐和IE
});
});
</script>
</head>
<body>
<a href="javascript:;" class="top">︿</a>
<!-- 页面内容 -->
<script>
for(var i=0;i<100;i++){
document.write("<h1>"+i+"</h1>");
}
</script>
</body>
</html>


2.用原生js实现回顶部特效的话,代码如下:

<!doctype html >
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title>Javascript 返回顶部</title>

<style type="text/css">
#btn {width:40px; height:40px; position:fixed; right:65px; bottom:10px;display: none; background:url(images/top_bg.png) no-repeat left top;}
#btn:hover {background:url(images/top_bg.png) no-repeat 0 -39px;}
.bg {width:1190px; margin:0 auto;}
</style>
<script src="script.js"></script>
</head>
<body>

<div class="bg">
<img src="images/tb_bg.jpg" alt="" />
</div>
<a href="javascript:;" id="btn" title="回到顶部"></a>
</body>
</html>


script.js

//页面加载完毕后触发
window.onload=function(){
var obtn=document.getElementById('btn');
var clientHeight=document.documentElement.clientHeight;//用来获取页面可视区的高度,便于回顶部按钮显示隐藏功能实现
var timer=null;

var isTop=true;//为了解决回滚时,中途控制了滚动条,迫使回滚停止
//滚动条滚动时触发
window.onscroll=function(){
//在滚动的时候判断是否已经到了第二屏
var osTop=document.documentElement.scrollTop||document.body.scrollTop;//分别兼容ie和chrome等其他浏览器
if(osTop>=clientHeight){
obtn.style.display='block';
}else{
obtn.style.display='none';
}
if(!isTop){
clearInterval(timer);
}
isTop=false;
}
obtn.onclick=function(){
//设置定时器
timer=setInterval(function(){
//首先获取滚动条到顶部的距离
var osTop=document.documentElement.scrollTop||document.body.scrollTop;//分别兼容ie和chrome等其他浏览器
var ispeed=Math.floor(-osTop/6);//回顶部一般是先快后慢,之所以加-号,是因为osTop-ispeed回滚的时候不会是0,所以还是会出现clearInterval失效
document.documentElement.scrollTop=document.body.scrollTop=osTop+ispeed;//因为上面为﹣号,所以这里为加号
isTop=true;
console.log(osTop-ispeed);
//如果不清楚定时器,则当回到顶部的时候拖动滚动条还继续回顶部
if(osTop==0){
clearInterval(timer);
}
},30);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: