gpt4 book ai didi

Meteor Iron Router - Router.go 回调可能吗?

转载 作者:行者123 更新时间:2023-12-04 08:34:48 28 4
gpt4 key购买 nike

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

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

}

});
}
});

最佳答案

除非您正在做一些花哨的事情,否则您可能不想使用 Router.go而是让 Iron-router 像往常一样管理 anchor 点击的路由。

就滚动到元素而言,这是 onAfterAction我正在使用的钩子(Hook),它支持任何路由和任何哈希( /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
});
});
}
});

关于Meteor Iron Router - Router.go 回调可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25301888/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com