返回顶部_demo

平时玩着新浪微博时,会发现右下角的“返回顶部”按钮挺好用的,实现这样的功能非常简单,今天趁着有空,也模仿着做了一个demo,效果见页面右下角。

由于原理相当简单,也没必要详细说明,主要是当滚动条拉下时,出现“返回顶部”按钮,点击就会迅速把页面往上滚。

其中最难搞的却是样式的设置,由于ie6以下版本不支持position:fixed,必须通过ie才支持的CSS expression进行绝对定位来模仿固定定位。

跨浏览器的固定定位样式,其中”_”符号只有 IE6 才能识别:

1position:fixed;
2bottom:50px;
3right:10px;
4_position:absolute;
5_bottom:auto;
6_top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-this.clientHeight-50));

这样做还不能使固定定位在ie6下平滑滚动,为文档添加空白图片竟然能神奇的解决,ie6实在是怪胎。

1 *html{
2 background:url(null);
3  }

css:

View Code
1 *html{
2 background:url(null);
3  }
4 .disable{
5 display:none;
6  }
7 .scrolltop{
8 font-size:16px;
9 width:16px;
10 background:#000;
11 color:#fff;
12 cursor:pointer;
13 position:fixed;
14 bottom:50px;
15 right:10px;
16 _position:absolute;
17 _bottom:auto;
18 _top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-this.clientHeight-50));
19 padding:5px 2px;
20 opacity:0.6;
21 filter:alpha(opacity=60);
22  }

js:

View Code
1 function scrollTop(){
2 dom=createDiv("返回顶部");
3 setCSS("disable");
4 dom.onclick=scrollAction;
5 window.onscroll=scrollEvent;
6
7 function createDiv(val){
8 var tem=document.createElement("div");
9 tem.innerHTML=val;
10 document.body.appendChild(tem);
11 return tem;
12 }
13 function setCSS(val){
14 dom.className=val;
15 }
16 function scrollEvent(){
17 document.documentElement.scrollTop?setCSS("scrolltop"):setCSS("disable");
18 }
19 function scrollAction(){
20 var html=document.documentElement,
21 step=Math.ceil(html.scrollTop/2);
22   html.scrollTop-=step;
23 if(html.scrollTop!==0){
24 setTimeout(arguments.callee,40);
25 }
26 }
27 }
28 scrollTop();
posted @ 2011-05-10 00:44  大G  阅读(495)  评论(0编辑  收藏  举报