JS点击返回页面顶部

LMS
1.4K+ 10

应从良未遂同学的要求,发一下我自己用的这个JS版点击返回页面顶部功能。我都忘记了这个功能是哪里偷来的了,最初有印象是在看到discuz论坛的返回顶部然后抠出来的,后来有没有再换过忘记了。

这个功能是目前比较通用的,就是没有滚动页面时不显示,滚动页面后固定显示在页面底部某个位置,点击后页面回到顶部。下面是代码:

首先是页面html代码,将它放到你的页面底部body结束前。

<a href="#" id="gotop" style="display: block; ">back up ↑</a>

然后是页面滚动后才显示点击按钮的JS代码

//backtotop
window.onscroll=backTop;
function backTop(){
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if(scrollTop==0){
document.getElementById('gotop').style.display="none";
}else{
document.getElementById('gotop').style.display="block";
}
}
backTop();
(function($) {
   var isTransitioned = true;
   var transparent = 0;
   var translucent = 0.3;
   var opaque = 1;
   $(function() {
      $("#goTop").fadeTo(0,translucent);
      $("#goTop").mouseover(function() {
         if(isTransitioned) {
            $(this).fadeTo("slow",opaque);
         }
      }).mouseout(function() {
         if(isTransitioned) {
            $(this).fadeTo("slow",translucent);
         }
      });
   });
})(jQuery);

下面是点击还回顶部的JS代码

jQuery(document).ready(function($){
$('#gotop').click(function(){$('html,body').animate({scrollTop: '0px'}, 600);return false;});
});

最后加上CSS,后面三行是解决IE下的问题的。

#gotop {
display: none;
position: fixed;
bottom: 20px;
left: 0;
text-indent: -9999px;
height: 40px;
width: 40px;
background: 
#666 url("images/top.png") center center no-repeat;
opacity: 0.6;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
_position: absolute;
_bottom: auto;
_top: expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-this.offsetHeight-(parseInt(this.currentStyle.marginTop,10)||20)-(parseInt(this.currentStyle.marginBottom,10)||20)));
}

看起来非常复杂,也许有更简单的吧。

THE END

评论 10

  1. 额,之前管理做论坛的时候遇到这个需求,还是在网上找代码,自己好像没写,这次学习了

  2. :roll: 其实不复杂的,你把那两个文件打包,然后模板里面要加的就一小段(css、js、link),呵呵。 :mrgreen:

        1. 呃。。。css有css加的地方,js有js加的地方,html放页面末尾就好。

          1. 本人非常不好意思的说,没有成功,在网上找了很多方法也都没有成功,真是见鬼了,放弃了

发表评论

Submit