Using HTML anchors in Ember.js

£可爱£侵袭症+ 提交于 2019-12-07 03:27:01

问题


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

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