本文介绍用原生JS和Jquery分别实现的网页goTopbutton功能,以及在这个过程中碰到的问题。
终于实现的效果类似:http://sc2.163.com/home(注意右下角的top)
代码:
Jquery
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
body{height: 2000px;}
#goTop{
display: none;
cursor:pointer;
background: url("common.png") no-repeat scroll 0 -460px;
position: fixed;
width: 60px;
height: 60px;
right: 20px;
bottom: 20px;
text-indent: -9999px;
z-index: 100;
}
#goTop:hover{
background-position: -100px -460px;
}
</style>
<script src="../jQuery/jquery-1.11.3.js"></script>
<script>
$(function(){
$(window).scroll(function(){
var scrH=document.documentElement.scrollTop+document.body.scrollTop;
if(scrH>200){
$('#goTop').fadeIn(400);
}else{
$('#goTop').stop().fadeOut(400);
}
});
$('#goTop').click(function(){
$('html,body').animate({scrollTop:'0px'},200);
});
});
</script>
</head>
<body>
<a id="goTop" href="javascript:">返回顶层</a>
</body>
</html>
JS
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
body{height: 2000px;}
#goTop{
display: none;
cursor:pointer;
background:url("common.png") no-repeat scroll 0 -460px;
position: fixed;
width: 60px;
height: 60px;
right: 20px;
bottom: 20px;
z-index: 100;
text-indent: -9999px;
}
#goTop:hover{
background-position: -100px -460px;
}
</style>
</head>
<body>
<a id="goTop" title="返回顶部" href="javascript:scroll(0,0)">返回顶层</a>
</body>
</html>
<script>
(function() {
function $(id){
return document.getElementById(id);
}
window.οnscrοll=function(){
var scrH=document.documentElement.scrollTop+document.body.scrollTop;
if(scrH>200){
$('goTop').style.display='block';
}else{
$('goTop').style.display='none';
}
};
}());
</script>
代码好像没啥特别好解释了。说说我碰到的问题吧。
①在IE低版本号下。不支持rgba属性~
②原生js的动画效果还不会实现,希望有人留言教下。