流星铁路由器 - Router.go回调可能吗?

时间:2014-08-14 06:59:19

标签: meteor iron-router

我有一个我希望用户按下的链接。当他们按下它时,路由器将转到某个模板,然后运行Smoothscroll.js代码来设置动画并向下滚动到锚标记。

      //When the user clicks on the link to get to the #contact anchor...
      //The code below does not work.
      Router.go('index');
      $('html,body').animate({
          scrollTop: $('#contact').offset().top
      }, 1200);

Router.go('index')效果很好。

      $('html,body').animate({
          scrollTop: $('#contact').offset().top
      }, 1200);

在索引模板上单独使用。

但是当我尝试一起运行它们时,路由器会转到索引,但滚动不起作用。

知道我该怎么做吗?

修改

这是我最新的Meteor 1.0+以及类似/#contact

的路径
Router.route('/', {
  name: 'index'
});

Router.onAfterAction(function() {
    var self = this;
    // always start by resetting scroll to top of the page
    $(window).scrollTop(0);
    // if there is a hash in the URL, handle it
    if (this.params.hash) {
        // now this is important : Deps.afterFlush ensures that iron-router rendering
        // process has finished inserting the current route template into DOM so we
        // can manipulate it via jQuery, if you skip this part the HTML element you
        // want to scroll to might not yet be present in the DOM (this is probably
        // why your code fails in the first place)
        Tracker.afterFlush(function() {

            if (typeof $("#" + self.params.hash).offset() != "undefined"){
                var scrollTop = $("#" + self.params.hash).offset().top;

                $("html,body").animate({
                    scrollTop: scrollTop
                });

            }

        });
    }
});

1 个答案:

答案 0 :(得分:4)

除非您正在做一些奇特的事情,否则您可能不想使用Router.go,而是让铁路由器像往常一样在锚定点击上管理路由。

就滚动到元素而言,这是我使用的onAfterAction钩子,它支持任何路由和任何哈希(/anyroute#anyhash)。

Router.onAfterAction(function() {
  // always start by resetting scroll to top of the page
  $(window).scrollTop(0);
  var hash=this.params.hash;
  // if there is a hash in the URL, handle it
  if (hash) {
    // now this is important : Tracker.afterFlush ensures that iron-router
    // rendering process has finished inserting the current route template
    // into DOM so we can manipulate it via jQuery, if you skip this part
    // the HTML element you want to scroll to might not yet be present in
    // the DOM (this is probably why your code fails in the first place)
    Tracker.afterFlush(function() {
      var element=$("#"+hash);
      var scrollTop = element.offset().top;
      $("html,body").animate({
        scrollTop: scrollTop
      });
    });
  }
});