我有一个有多个页面的流星应用程序。我希望能够深度链接到页面中间的某个锚。
传统上,在普通的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的滚动方法。JQuery就是一个这样的例子:(你可以把它放在你的链接/按钮点击处理程序中)
Template.hello.events({
'click #theitemtoclick':function(e,tmpl) {
e.preventDefault();
$('html, body').animate({
scrollTop: $("#item_id").offset().top
}, 600);
}
});
然后用id:标记你的html项目
<h1 id="item_id">Section X</h1>
目前,IronRouter中存在从url中删除哈希的问题。这在这里和这里讨论。幸运的是,有一个修复程序,尽管它似乎没有在稳定版本中。
我的铁路由器解决方案与传统的锚标签:
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中。
不管是好是坏,这都将通过代码推送再次滚动。
Mike的Answer对我来说不太管用。在onRendered回调中,散列返回为空。我将代码嵌套在一个额外的Meteor.setTimeout
中
fyi我在用Blaze。
下面的效果很有魅力:)
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;
};