【问题标题】:I want my function to be triggered when the route changes我希望在路线更改时触发我的功能
【发布时间】:2014-07-24 16:22:17
【问题描述】:

我有一个函数可以更改类的 css,并且我希望该函数在路由更改时调用。我还希望将此逻辑放置在 ApplicationView 中,以便在路线更改的任何时间任何地点调用它。

由函数更改的类(我们将调用该类.float-right-col)在我的应用程序中的每个.hbs 模板上创建一次。

<div class="float-right-col">
</div>

我想要的伪代码

Whenever we are transitioned to a new route {
  Set the css of float-right-col to this by toggle classes with overriding attributes
}

为简单起见我遗漏的信息(可选)又名大图:

最终上面提到的伪代码会有另一个条件&amp;&amp;,要求屏幕大于800px。

Whenever we are transitioned to a new route {
  check if the screen size is below 800px & if it is {
    Set the css of float-right-col to this
  }
}

理想情况下,css 只知道屏幕大小并在页面加载之前调整 css。 使用上面的伪代码,页面将加载默认 css,然后调用该函数使 float-right-col 转换到新位置。

要切换此元素的 css,我将这两个类添加和删除到 .float-right-col

 .openCol {
    position:absolute;
    right: 0px;
    transition: all .2s ease 0s;
  }
  .closeCol {
    position:fixed;
    right: -290px;
    transition: all .2s ease 0s;
  }  

我也尝试过使用 .css()

最后,我尝试了媒体查询,但这些似乎只适用于第一页的初始加载

@media screen and (max-width: 800px) {
  .float-right-col {
    position: fixed !important;
    right: -290px;
  }
}

【问题讨论】:

  • “路线变更”是什么意思?
  • 只要您的所有“路由”具有相同的样式表文件,媒体查询就应该适用于每个“路由”。如果您正在使用 SPA 并希望在“路由”更改后立即引发事件,您应该查看框架的 API,它可能会公开此类事件。另一种方法是使用 setInterval 并检查 window.location 是否已更改并自己抛出事件。
  • @LinuxN00b 我确实在标签中提到了框架。 Ember.js
  • @PabloMatíasGomez 当 url 改变时。所以从 users.hbs -> locations.hbs 链接
  • @Kevkong 我对每条路线都有相同的样式表,但它不起作用。你能澄清一下什么是SPA吗?

标签: javascript jquery html css ember.js


【解决方案1】:

您可以观察 ApplicationController 中的 currentPath 并对任何更改做出反应。

App.ApplicationController = Ember.Controller.extend({
  currentPathChanged: function() {
    console.log(this.get('currentPath'));
  }.observes('currentPath')
});

【讨论】:

  • 这行得通!我遇到的一个问题是,当我路由到根“/”时,它并不认为我正在更改路由。有没有好的解决方法?
  • 对不起,我是个 jsbin 菜鸟,但我似乎无法让它工作。我还看到这种 css 更改不会发生在 /users 等其他页面中,但在 /records 中,它确实有效。我想我已经缩小了问题的范围。每次我更改路由时都会调用该函数,但也许它认为users中的.float-right-col使用Jquery调用与float-right-col中的/users中的/users不同
  • 你想完成类似的事情吗? google-developers.appspot.com/web/fundamentals/resources/… 。调整浏览器窗口大小以查看效果。
  • 是的,在该示例中使用侧边栏。当屏幕较小时,我使用right 将列部分推离屏幕。
  • 那么我会向您推荐多设备布局的网络基础知识。 google-developers.appspot.com/web/fundamentals/layouts 。在您的情况下,媒体查询将是 right way 来解决问题。
猜你喜欢
  • 2019-02-27
  • 1970-01-01
  • 2022-10-06
  • 2022-01-08
  • 2015-12-23
  • 2020-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多