複数のページを持つ流星アプリがあります。ページの途中にあるアンカーにディープリンクできるようにしたいと考えています。
従来、通常の html では、ページのどこかに を作成し、/mypage.html#chapter5 経由でリンクします。
これを行うと、流星アプリはその場所までスクロールしません。
このあたりの最善のアプローチは何ですか?
複数のページを持つ流星アプリがあります。ページの途中にあるアンカーにディープリンクできるようにしたいと考えています。
従来、通常の html では、ページのどこかに を作成し、/mypage.html#chapter5 経由でリンクします。
これを行うと、流星アプリはその場所までスクロールしません。
このあたりの最善のアプローチは何ですか?
@Akshat の回答は同じページで機能しますが、「#」を含む URL を渡すことができるようにしたい場合はどうすればよいでしょうか。私は流星のドキュメントが行った方法でそれを行いました。
Template.myTemplate.rendered = function() {
var hash = document.location.hash.substr(1);
if (hash && !Template.myTemplate.scrolled) {
var scroller = function() {
return $("html, body").stop();
};
Meteor.setTimeout(function() {
var elem = $('#'+hash);
if (elem.length) {
scroller().scrollTop(elem.offset().top);
// Guard against scrolling again w/ reactive changes
Template.myTemplate.scrolled = true;
}
},
0);
}
};
Template.myTemplate.destroyed = function() {
delete Template.myTemplate.scrolled;
};
ソースからメテオ ドキュメントに盗まれました。
ある種の JavaScript ルーターを使用していますか? メテオルーター?
JavaScriptベースのスクロール方法のようなものを使用できます。そのような例の 1 つが JQuery です: (これをリンク/ボタンのクリック ハンドラに配置できます)。
Template.hello.events({
'click #theitemtoclick':function(e,tmpl) {
e.preventDefault();
$('html, body').animate({
scrollTop: $("#item_id").offset().top
}, 600);
}
});
次に、アンカーを配置する html アイテムに ID でタグを付けます。
<h1 id="item_id">Section X</h1>
現在、IronRouter にはハッシュが URL から削除されるという問題があります。これについては、こちらとこちらで説明しています。幸いなことに、安定版にはないように見えますが、修正があります。
従来のアンカー タグを使用した私の Iron Router ソリューション:
1) 上記の IronRouter 修正を適用します。
2)
Router.configure({
...
after: function () {
Session.set('hash', this.params.hash);
},
...
});
3)
function anchorScroll () {
Deps.autorun(function (){
var hash = Session.get('hash');
if (hash) {
var offset = $('a[name="'+hash+'"]').offset();
if (offset){
$('html, body').animate({scrollTop: offset.top},400);
}
}
Session.set('hash', '');
});
}
Template.MYTEMPLATE.rendered = function (){
anchorScroll();
};
残念ながら、これは各テンプレートで設定する.rendered()
必要があります。そうしないと、アンカー タグが DOM にあることが保証されません。
良くも悪くも、これはコードプッシュで再びスクロールします。
マイクの答えは私にはうまくいきませんでした。onRendered コールバックでハッシュが空を返していました。コードを追加でネストしましたMeteor.setTimeout
参考までに、私はブレイズを使用しています。
以下は魅力のように機能しました:)
Template.myTemplate.onRendered(function() {
Meteor.setTimeout(function(){
var hash = document.location.hash.substr(1);
if (hash && !Template.myTemplate.scrolled) {
var scroller = function() {
return $("html, body").stop();
};
Meteor.setTimeout(function() {
var elem = $("a[name='" + hash + "']");
if (elem.length) {
scroller().scrollTop(elem.offset().top);
// Guard against scrolling again w/ reactive changes
Template.myTemplate.scrolled = true;
}
},
0);
}
},0);
});
Template.myTemplate.destroyed = function() {
delete Template.myTemplate.scrolled;
};