Scroll to anchor link in a Sammy.js project

梦想与她 提交于 2019-12-14 02:00:17

问题


I am building a website using the sammy.js framework. I have a sidebar that is constant, and the main content view which loads the different pages with the help of sammy. On the side bar I have links to news articles. Currently any of the article links on the sidebar just load the #/news route. But I'd like it load the route and scroll down to the article. I've tried having an anchor link trigger once the route is loaded to scroll down to the article, but I get errors with the sammy app. Any thoughts on how this could be accomplished?


回答1:


Seems like an old question but since it's still unanswered....

You have to define your URL as a regular expression, and allow an optional bookmark hash at the end of it:

get(/#\/news(#.+)?/, function() {
    var articleId = this.params['splat'];
});

This will match any of the following routes:

  • #/news
  • #/news#
  • #/news#my-news-article

You should then be able to use the articleId to find the matching element and manually scroll. e.g. in the last route above, 'articleId' will be '#my-news-article', so using jQuery you could do something like:

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

Hope that helps.



来源:https://stackoverflow.com/questions/9351231/scroll-to-anchor-link-in-a-sammy-js-project

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!