Hello Js

导航

javascript 回到顶部

最近做的一个小项目中需要用到这个功能,在网上看了下 很多是用jquery写的,因为要加个回到顶部就给页面多引用一个jquery 实在是有些多余了,自己就写了一个。

大概的原理:

在高级的浏览器下 采用fixed的postion属性,在IE6下,则延迟的设置对应标签的top值。代码贴过来:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>t</title>
<meta http-equiv="content-type" content="text/html;charset=gb2312">
<style type="text/css">
.backToTop {
 display: none;
 width: 18px;
 line-height: 1.2;
 padding: 5px 0;
 background-color: #000;
 color: #fff;
 font-size: 12px;
 text-align: center;
 position: fixed;
 _position: absolute;
 right: 10px;
 bottom: 100px;
 _bottom: "auto";
 cursor: pointer;
 opacity: .6;
 filter: Alpha(opacity=60);
}
</style>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>
<body>

<div style="height:2000px;"></div>
<script type="text/javascript">
(function() {
    var timer;
    if(!document.getElementById("topBtn")){
        var d = document.createElement("div");
        d.className = "backToTop";
        d.id = "btn";
        d.innerHTML = "to top";
        document.body.appendChild(d);
    }

    var backToTopFun = function() {
        btn.style.display = "none"
        if(timer){
            clearTimeout(timer);
        }
        timer = setTimeout(function(){
            var st = document.documentElement.scrollTop||document.body.scrollTop ;
            var winh = document.documentElement.clientHeight;
            var btn = document.getElementById("btn");

           if (!window.XMLHttpRequest) {
                btn.style.top = (st + winh - 166)+"px";
            }
            (st > 0)? btn.style.display = "block" : btn.style.display = "none";
        },100)
        
    };
    window.onscroll = function(){
        backToTopFun();
    }
    document.getElementById("btn").onclick = function(){
        window.scrollTo(0,0);
    }
})();
</script>
</body>
</html>

这里要说明的 一个是滚动条的高度 一个是浏览器的可视高度(也就是document的高度),我这里做了一个延迟的处理。目的是,在用户进行滚动条滚动的时候,不用实时的执行,这样视觉上看到的是:当滚动滚动条时,回到顶部按钮消失,松开,又出现在固定的位置。

以前在微博的时候 我记得曾研究过那里的回到顶部功能,大概也有个延时的动作,具体的记不得了。刚在微博首页 看了下微博的回到顶部按钮 是紧贴在中间的微博信息旁边的 而且是一直出现的。

posted on 2012-11-13 17:15  苏拉A梦  阅读(289)  评论(0编辑  收藏  举报