[MooTools] Fx.SmoothScroll – not add the address bar URL’s hash

Dojo触ってて思い出した事を解決。

MooTools MoreのFx.SmoothScrollはスクロールが終了した時にアドレスバーのURLにハッシュ(#top など)を追加しますが、
少しカスタマイズすればこれを追加しないように変更することが出来ます。

以下は未圧縮ソースです。

var SmoothScroll = Fx.SmoothScroll = new Class({

	Extends: Fx.Scroll,

	initialize: function(options, context){
		context = context || document;
		this.doc = context.getDocument();
		var win = context.getWindow();
		this.parent(this.doc, options);
		this.links = $$(this.options.links || this.doc.links);
		this.hash = this.options.hash; // Add this line
		var location = win.location.href.match(/^[^#]*/)[0] + '#';
		this.links.each(function(link){
			if (link.href.indexOf(location) != 0) {return;}
			var anchor = link.href.substr(location.length);
			if (anchor) this.useLink(link, anchor);
		}, this);
		if (!Browser.Engine.webkit419 && this.hash) { // Add the "&& this.hash"
			this.addEvent('complete', function(){
				win.location.hash = this.anchor;
			}, true);
		}
	},

	useLink: function(link, anchor){
		var el;
		link.addEvent('click', function(event){
			if (el !== false && !el) el = document.id(anchor) || this.doc.getElement('a[name=' + anchor + ']');
			if (el) {
				event.preventDefault();
				this.anchor = anchor;
				this.toElement(el).chain(function(){
					this.fireEvent('scrolledTo', [link, el]);
				}.bind(this));
				link.blur();
			}
		}.bind(this));
	}
});

変更箇所はコメントをつけた2箇所だけ。
この修正によりhashオプションで表示/非表示の切り替えが出来るようになります。

new SmoothScroll({hash:true}); //the hash appear on the address bar 

ハッシュが全く必要ないという場合は以下をコメントアウトしてもいいです。

win.location.hash = this.anchor;

圧縮ソース:

var SmoothScroll=Fx.SmoothScroll=new Class({Extends:Fx.Scroll,initialize:function(b,c){c=c||document;this.doc=c.getDocument();var d=c.getWindow();
this.parent(this.doc,b);this.links=$$(this.options.links||this.doc.links);this.hash=this.options.hash;var a=d.location.href.match(/^[^#]*/)[0]+"#";this.links.each(function(f){if(f.href.indexOf(a)!=0){return;
}var e=f.href.substr(a.length);if(e){this.useLink(f,e);}},this);if(!Browser.Engine.webkit419&&this.hash){this.addEvent("complete",function(){d.location.hash=this.anchor;
},true);}},useLink:function(c,a){var b;c.addEvent("click",function(d){if(b!==false&&!b){b=document.id(a)||this.doc.getElement("a[name="+a+"]");}if(b){d.preventDefault();
this.anchor=a;this.toElement(b).chain(function(){this.fireEvent("scrolledTo",[c,b]);}.bind(this));c.blur();}}.bind(this));}});

コメントを残す

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください