我有一个包含多个页面的流星应用程序。我希望能够在页面中间的某个位置深度链接到锚点。
传统上,在普通的html中,你会在你的页面中创建一个地方,并通过/mypage.html#chapter5链接到它。
如果我这样做,我的流星应用程序将不会向下滚动到该位置。
围绕此问题的最佳方法是什么?
答案 0 :(得分:7)
答案 1 :(得分:4)
您使用某种javascript路由器吗?流星路由器?
您可以使用类似基于javascript的滚动方法。一个这样的例子是使用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>
答案 2 :(得分:1)
目前,IronRouter存在一个问题,即从网址中删除哈希值。我们讨论了here和here。幸运的是there is a fix,即使它似乎不是稳定版本。
我的铁路由器解决方案与传统的锚标签:
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中。
无论好坏,这将通过代码推送再次滚动。
答案 3 :(得分:0)
Mike's Answer对我不起作用。哈希在onRendered回调中返回空。我将代码嵌套在另外的Meteor.setTimeout
我正在使用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;
};