使用jQuery改善”Return to Top”

作者: nick 分类: js 发布时间: 2010-05-16 02:50 ė 6没有评论

传统的”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


其对应的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事件

$document.ready(function() {
 
   $('a.return-to-top').click(function() {
     $('html').animate({scrollTop: 0}, 'fast');
     $('body').animate({scrollTop: 0}, 'fast');
     return false;
   });
 });

第5行是专门为chrome和safari而追加的(感谢Wyatt同学提醒)
参考http://stackoverflow.com/questions/1830080/jquery-scrolltop-doesnt-seem-to-work-in-safari-or-chrome-windows

好了,大功告成了。其实需要写的代码很少,真是赞叹jQuery的强大:D

本文出自 传播、沟通、分享,转载时请注明出处及相应链接。

本文永久链接: https://www.nickdd.cn/?p=449

发表评论

您的电子邮箱地址不会被公开。

Ɣ回顶部