原帖地址:http://space.flash8.net/space/?uid-18713-action-viewspace-itemid-409746
原作者:我佛山人
代码
//
更平滑的滚动效果
var SmoothScroll = new Class({
// 继承自Fx.Scroll
Extends: Fx.Scroll,
// 构造函数,将覆盖父类Fx.Scroll的构造函数
initialize: function (options, context) {
// 限定所作用的对象
context = context || document;
var doc = context.getDocument(), win = context.getWindow();
// 调用父类Fx.Scroll的构造函数
arguments.callee.parent(doc, options);
// 获取所有链接
this .links = ( this .options.links) ? $$( this .options.links) : $$(doc.links);
// 获取不包括锚点的当前页地址
var location = win.location.href.match( / ^[^#]* / )[ 0 ] + ' # ' ;
// 遍历所有链接,只处理锚点在当前页的锚点链接
this .links.each( function (link) {
// 链接不是当前页的锚点
if (link.href.indexOf(location) != 0 ) return ;
// 取锚点(这里直接用link.hash应该更简单)
var anchor = link.href.substr(location.length);
// 取到锚点名,然后为当前链接添加事件监听,在单击时将自动滚动到id值为锚点名的对象
if (anchor && $(anchor)) this .useLink(link, anchor);
}, this );
// 对Safari的hack处理
if ( ! Browser.Engine.webkit419) this .addEvent( ' onComplete ' , function () {
win.location.hash = this .anchor;
}, true );
},
// 使用当前链接,对当前链接的事件监听处理
useLink: function (link, anchor) {
// 监听链接的单击事件
link.addEvent( ' click ' , function (event) {
// 转为属性,使得在其它方法或事件内可以使用
this .anchor = anchor;
// 滑动到id为anchor的对象
this .toElement(anchor);
// 阻止事件冒泡及返回值
event.stop();
}.bind( this ));
}
});
var SmoothScroll = new Class({
// 继承自Fx.Scroll
Extends: Fx.Scroll,
// 构造函数,将覆盖父类Fx.Scroll的构造函数
initialize: function (options, context) {
// 限定所作用的对象
context = context || document;
var doc = context.getDocument(), win = context.getWindow();
// 调用父类Fx.Scroll的构造函数
arguments.callee.parent(doc, options);
// 获取所有链接
this .links = ( this .options.links) ? $$( this .options.links) : $$(doc.links);
// 获取不包括锚点的当前页地址
var location = win.location.href.match( / ^[^#]* / )[ 0 ] + ' # ' ;
// 遍历所有链接,只处理锚点在当前页的锚点链接
this .links.each( function (link) {
// 链接不是当前页的锚点
if (link.href.indexOf(location) != 0 ) return ;
// 取锚点(这里直接用link.hash应该更简单)
var anchor = link.href.substr(location.length);
// 取到锚点名,然后为当前链接添加事件监听,在单击时将自动滚动到id值为锚点名的对象
if (anchor && $(anchor)) this .useLink(link, anchor);
}, this );
// 对Safari的hack处理
if ( ! Browser.Engine.webkit419) this .addEvent( ' onComplete ' , function () {
win.location.hash = this .anchor;
}, true );
},
// 使用当前链接,对当前链接的事件监听处理
useLink: function (link, anchor) {
// 监听链接的单击事件
link.addEvent( ' click ' , function (event) {
// 转为属性,使得在其它方法或事件内可以使用
this .anchor = anchor;
// 滑动到id为anchor的对象
this .toElement(anchor);
// 阻止事件冒泡及返回值
event.stop();
}.bind( this ));
}
});