【问题标题】:Named anchor in a Single Page Application (SPA)单页应用程序 (SPA) 中的命名锚点
【发布时间】:2013-02-11 02:04:19
【问题描述】:

在 SPA 中,使用 Sammy.js 等导航框架,我如何在页面中使用名为锚点的页面进行页面内导航?

例如假设我有一个类似localhost/myapp/#/somerecord/1 的路由,应用程序在其中加载 id = 1 的 somerecord

然而 somerecord 真的很复杂很长。我希望能够使用命名锚点跳转到某个部分。

假设文章元素被定义为<article id=section-d> ... </article>,我只是链接到<a href=#section-d>Section D</a>,它在技术上是有效的,但URL 看起来像localhost/myapp/#section-d,这会破坏导航堆栈。点击返回按钮让我回到localhost/myapp/#/somerecord/1 并且没有跳回顶部。

首选的操作是跳回顶部或上一页。关于如何实现这一点的任何想法?

【问题讨论】:

标签: html single-page-application sammy.js


【解决方案1】:

实际上,您必须将您的 URL 定义为正则表达式,并在其末尾允许可选的书签哈希;类似:

get(/#\/somerecord\/(\d+)(#.+)?/, function() {
    var args = this.params['splat'];
    var recordId = args[0];
    var articleId = args[1];
});

这应该匹配以下任何路由:

  • #/somerecord/1
  • #/somerecord/1#(视为没有文章id)
  • #/somerecord/1#section-d (articleId = '#section-d')

然后您应该能够使用 articleId 找到匹配的元素并手动滚动。例如在上面的最后一条路线中,使用 jQuery 您可以执行以下操作:

var $article = $(articleId);
    $(document.body).animate({ scrollTop: $article.offset().top });
});

我刚刚写了一篇更全面的文章(使用 Durandal),如果您有兴趣:http://quickduck.com/blog/2013/04/23/anchor-navigation-durandal/

编辑 链接死了。文章在这里http://decompile.it/blog/2013/04/23/anchor-navigation-durandal/

【讨论】:

    【解决方案2】:

    我在使用 durandal 和 sammy.js 时遇到了同样的问题。基本上,您必须为页面上所需的每个锚点创建一个(不可见的)路由。请参阅我关于我找到的解决方案的帖子:http://papamufflon.blogspot.de/2013/04/durandal-scrollspy.html

    【讨论】:

      猜你喜欢
      • 2013-07-31
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多