简体   繁体   English

EmberJS-路线后如何滚动到插座?

[英]EmberJS - How to scroll to outlet after a Route?

My application template : 我的应用程序模板:

<div class ="row">
  <div class="hide-for-large-only small-12 text-center columns">
    <h1 class="subheader"> Departments </h1>
  </div>
  <div class="small-12 large-3 large-pull-1 columns">
    <ul class="no-bullet sid-nav">
      <li>{{#link-to "Departments.Foo"}}Foo{{/link-to}}</li>
      <li>{{#link-to "Departments.Bar"}}Bar{{/link-to}}</li>
      <li>{{#link-to "Departments.FooBar"}}FooBar{{/link-to}}</li>
      <li>{{#link-to "Departments.BarFoo"}}BarFoo{{/link-to}}</li>
    </ul>
  </div>

  <div class="small-12 large-9 columns ">
    {{outlet}}
  </div>
</div>

For Desktop version, scrolling to top of window seems fine. 对于桌面版,滚动到窗口顶部似乎很好。

App.ApplicationController = Em.Controller.extend({
  currentPathChanged: (function() {
    return window.scrollTo(0, 0);
  }).observes("currentPath")
});

But in Mobile version, on clicking the link the change of content goes unnoticed at bottom as {{outlet}} goes below the side nav. 但是在移动版本中,单击链接后,{{outlet}}转到侧面导航下方,内容的更改在底部没有引起注意。 So how to auto scroll to {{outlet}} after a Route ? 那么如何在路由后自动滚动到{{outlet}}?

You need to ensure that the window.scrollTo call occurs after the new view (on route change) has fully rendered. 您需要确保在完全渲染新视图(更改路线)之后发生window.scrollTo调用。 Ember.js provides a queue exactly for that: afterRender . Ember.js为此提供了一个队列: afterRender

Let's define a mixin that you can use in a view, so that whenever that view has rendered, it scrolls the window to the starting position of its template: 让我们定义一个可以在视图中使用的mixin,这样,只要渲染了该视图,它就会将窗口滚动到其模板的起始位置:

App.ScrollToMixin = Ember.Mixin.create({
  setupScrollToOutlet: function() {
    Ember.run.scheduleOnce('afterRender', this, function(){
      var position = this.$().offset().top;
      window.scrollTo(0, position);
    });
  }.on('didInsertElement')
});

Let's say you visit the posts route and the outlet is far down into the page. 假设您访问了posts路线,而分支机构已深入到页面中。 Include the App.ScrollToMixin into the App.PostsView , and it will scroll the window to the posts.handlebars starting position: App.ScrollToMixin包含到App.PostsView ,它将把窗口滚动到posts.handlebars起始位置:

App.PostsView = Ember.View.extend(App.ScrollToMixin);

Demo: http://emberjs.jsbin.com/miqakovu/4/edit 演示: http : //emberjs.jsbin.com/miqakovu/4/edit

This doesn't have much to do with Ember.js, this is straight Javascript (or jQuery if you prefer). 这与Ember.js无关,这是直接的Javascript(如果您愿意,也可以是jQuery)。 First, add an ID or unique class: 首先,添加一个ID或唯一类:

<div class="small-12 large-9 columns" id="outlet_div">
    {{outlet}}
</div>

Then, to scroll to it: 然后,滚动到它:

window.scrollTo(0, $('#outlet_div').offset().top);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM