9

我有一个多页的流星应用程序。我希望能够深度链接到页面中间某处的锚点。

传统上,在普通的 html 中,您会在页面中创建一个位置,并通过 /mypage.html#chapter5 链接到它。

如果我这样做,我的流星应用程序将不会向下滚动到该位置。

最好的方法是什么?

4

4 回答 4

7

@Akshat 的答案适用于同一页面,但是如果您希望能够传递带有“#”的网址怎么办?我按照流星文档的方式做到了。

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;
};

源头窃取到流星文档。

于 2013-12-14T01:21:45.057 回答
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>
于 2013-07-17T11:22:20.103 回答
1

目前,IronRouter 中存在从 url 中删除哈希的问题。这在此处此处进行了讨论。幸运的是,有一个修复程序,即使它似乎不在稳定版本中。

带有传统锚标签的 My 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 中。

无论好坏,这将通过代码推送再次滚动。

于 2013-12-27T20:32:01.013 回答
0

迈克的回答对我不太有效。哈希在 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;
};
于 2016-08-07T18:53:25.037 回答