Atea - Hero's Grave

面向对象,开源,框架,敏捷,云计算,NoSQL,商业智能,编程思想。

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  40 随笔 :: 0 文章 :: 28 评论 :: 0 Trackbacks
传统的"Return to Top"置于页面底部或指定位置,点击后返回页面顶部。
但其存在诸多不便:
1、页面顶部必须定义一个相应的锚点,其本身也会占用DOM空间,很容易发生返回的不是绝对的顶部而是该锚点(滚动条会稍微向下一点,而不是在0的位置)
2、如果页面很长,想在滚动条任意处回顶部会变得难以处理。

使用jQuery能大大改善这一用户体验。本文章将能做到:
"Return to Top"在页面初始化时不显示,当移动滚动条时出现并随滚动条位置变化而变化。
点击"Return to Top"页面移动到顶部,当滚动条到顶部时"Return to Top"自动隐藏。
以上均伴有动画效果。
在线Demo:http://atealxt.appspot.com/guestbook
下载实例:http://www.blogjava.net/Files/atealxt/returnToTop.zip

首先有一个DIV
<div id="switcher">
  
<href="#top" class="return-to-top">Return to Top</a>
</div>

其对应的CSS为
#switcher {
  position
: absolute;
  width
: 90px;
  padding
: .5em;
  border
: 1px solid #777;
  background
: #ddd;
}
.return-to-top 
{
  clear
: left;
}

在document.ready中令"Return to Top"移动到页面最右边,并隐藏。
$switcher.animate({
    'left': $('#container').outerWidth() 
- $switcher.outerWidth()
  }, 
function() {
       $document.bind('scroll', moveSwitcher);
     }
);
$switcher.hide();
绑定scroll事件要注意,要想支持IE6的话,必须用$window来绑定scroll事件。

函数moveSwitcher实现"Return to Top"随滚动条移动而移动。
这里设定了一个事件延迟捕捉,以达到动画效果。
var moveSwitcher = function() {
    
  
var delay = 500;
  
var executionTimer;
  
return function() {
    
if (!!executionTimer) {
      clearTimeout(executionTimer);
    }
    
    executionTimer 
= setTimeout(function() {
      $switcher.animate({ 'top': $window.height() 
+ $document.scrollTop() - $switcher.height() - 25 }, 'slow', slideSwitcher);
    }, delay);
  };
}();

函数slideSwitcher为页面移动到顶部时隐藏"Return to Top"。
var slideSwitcher = function() {
  
if ($document.scrollTop() == 0) {
    $switcher.slideUp('fast');
  } 
else {
    $switcher.slideDown('fast');
  }
};

为了完善这一效果,我们给resize事件也绑定moveSwitcher
$window.resize(function(){
  $switcher.animate({ 'left': $('#container').outerWidth() 
- $switcher.outerWidth() } , moveSwitcher);
});

最后,给"Return to Top"添加onclick事件
1 $document.ready(function() {
2 
3   $('a.return-to-top').click(function() {
4     $('html').animate({scrollTop: 0}, 'fast');
5     $('body').animate({scrollTop: 0}, 'fast');
6     return false;
7   });
8 });
第5行是专门为chrome和safari而追加的(感谢Wyatt同学提醒)
参考http://stackoverflow.com/questions/1830080/jquery-scrolltop-doesnt-seem-to-work-in-safari-or-chrome-windows

好了,大功告成了。其实需要写的代码很少,真是赞叹jQuery的强大:D
posted on 2010-05-13 11:14 Atea 阅读(2154) 评论(2)  编辑  收藏 所属分类: Javascript

评论

# re: 使用jQuery改善"Return to Top" 2010-05-13 11:32 Wyatt
chrome里面不好使~~  回复  更多评论
  

# re: 使用jQuery改善"Return to Top" 2010-05-13 13:16 Atea
@Wyatt
谢谢提醒,已修改:P  回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航: