Scroll to anchor link in a Sammy.js project

2019-07-17 19:43发布

问题:

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.