滚动返回顶部代码

Javascript 1620 0 2012-12-25

滚动返回顶部代码

HTML CODE:
<a name="top" id="top"></a>
<div style="height:1500px; width:10px; background:#0099FF">asdf</div>
<a href="javascript:void(0)" onclick="goto_top()">返回页顶</a>

JS CODE:
<script language="javascript">
//<![CDATA[
var goto_top_type = -1;
var goto_top_itv = 0;

function goto_top_timer()
{
var y = goto_top_type == 1 ? document.documentElement.scrollTop : document.body.scrollTop;
var moveby = 15;

y -= Math.ceil(y * moveby / 100);
if (y < 0) {
y = 0;
}

if (goto_top_type == 1) {
document.documentElement.scrollTop = y;
}
else {
document.body.scrollTop = y;
}

if (y == 0) {
clearInterval(goto_top_itv);
goto_top_itv = 0;
}
}

function goto_top()
{
if (goto_top_itv == 0) {
if (document.documentElement && document.documentElement.scrollTop) {
goto_top_type = 1;
}
else if (document.body && document.body.scrollTop) {
goto_top_type = 2;
}
else {
goto_top_type = 0;
}

if (goto_top_type > 0) {
goto_top_itv = setInterval('goto_top_timer()', 50);
}
}
}
//]]>
</script>

上一篇:jQuery插件实现光标处插入文本

下一篇:javascript的URL编码和解码

讨论数量:1

天涯网魂 3 杠 5 星2012-12-25 11:08:01

<!--[if lt IE 7]>
<style type="text/css">
#gotopbtn{position:absolute;top:expression(eval(document.documentElement.scrollTop + 50));}
</style>
<![endif]-->
<style type="text/css">
body{
font:12px Verdana, Geneva, sans-serif;
line-height:1.2;
text-align:center;
margin:0px; 
}
#gotopbtn {
width:100px;
height:30px;
background:#fff;
position:fixed;
bottom:100px;
right:20px;
display:none;
cursor:pointer;
font-size:14px;
line-height:30px;
border:1px solid #aaa; 
}
.main{
width:100%;
background:#ccc;
height:1500px;
margin:0 auto;
}
</style>

HTML CODE:
<div class="main">头部在这里哦!!</div>
<div id="gotopbtn">返回顶部</div>

JS CODE:
<script type="text/javascript">
backTop=function (btnId){
var btn=document.getElementById(btnId);
var d=document.documentElement;
window.onscroll=set;
btn.onclick=function (){
   btn.style.display="none";
   window.onscroll=null;
   this.timer=setInterval(function(){
    d.scrollTop-=Math.ceil(d.scrollTop*0.1);
    if(d.scrollTop==0) clearInterval(btn.timer,window.onscroll=set);
   },10);
};
function set(){btn.style.display=d.scrollTop?'block':"none"}
};
backTop('gotopbtn');
</script>

请先登录再发表讨论。 2024-05-02

天涯网魂
3 杠 5 星
TA 的文章
TA 的随言
TA 的资源链