问题
In my Ember application, how can I jump to an HTML anchor inside one of my Handlebars templates? I created a jsFiddle that shows what I want to accomplish.
Background
Ember's model of navigation through an application uses HTML anchors.
I have the following requirement: when a user clicks on a Handlebar linkTo helper to navigate to a new route destination, the browser should automatically scroll to an anchor inside the Handlebars template associated to that new route destination.
回答1:
Use jquery to scroll to a particular section.
$('html,body').animate({
scrollTop: $("a[name='someAnchor']").offset().top
});
Refer this SO answer regarding the same.
To scroll to the anchor after the view is rendered override the didInsertElement in your definition for your route's View.
Refer this SO answer regarding the same.
App.LonglistView = Ember.View.extend({
didInsertElement: function() {
// Place the scroll to anchor code here.
$('html,body').animate({
scrollTop: $("a[name='someAnchor']").offset().top
});
}
});
Here is a working example in jsfiddle ( I have not added any data models for clarity )
EDIT: You could also use non-jquery way to do the scrolling
document.getElementsByTagName('a')[name='someAnchor'].scrollIntoView()
The jsfiddle example for the same.
来源:https://stackoverflow.com/questions/16489533/using-html-anchors-in-ember-js