meteor js iron router:路由更改时应用CSS更改

DeB*_*aid 5 javascript css meteor iron-router meteor-blaze

我的应用程序中有主页,联系页面和其他几个与产品相关的页面.

目标是将背景图像应用于ONLY特定路线:/homepage/contact.如果用户离开任一路线,请应用一些css更改.

我现在正在我的主页上用帮助器一起攻击这个,如下所示:

Template.homepage.rendered = function () {

    var route = Router.current();

    if ( route.path == '/' ) {

        document.body.className = "showBackgroundImage";

    }
};
Run Code Online (Sandbox Code Playgroud)

部分胜利在这里,因为这将激活css,但我需要在路线改变时停用.我也尝试了以下内容router.js:

this.route('homepage', {
    path: '/', 
    onAfterAction: function  (argument) {
       // add a class name to body
       document.body.className = "showBackgroundImage";
    }
  });
Run Code Online (Sandbox Code Playgroud)

和CSS在后台标准:

.showBackgroundImage { 
  background: url(bgImage.jpg) no-repeat center center fixed; 
}
Run Code Online (Sandbox Code Playgroud)

sai*_*unt 6

这可以通过iron:router布局轻松完成,并通过路由为每个页面应用不同的类.

首先,您需要定义主布局,例如:

<template name="mainLayout">
  <!-- optional navbar yield -->
  {{> yield region="navbar"}}
  <div class="{{currentRouteName}}-page">
    {{> yield}}
  </div>
  <!-- optional footer yield -->
  {{> yield region="footer"}}
</template>
Run Code Online (Sandbox Code Playgroud)

currentRouteName助手应该是这个样子:

UI.registerHelper("currentRouteName",function(){
  return Router.current()?Router.current().route.getName():"";
});
Run Code Online (Sandbox Code Playgroud)

然后我建议将a关联RouteController到主布局,作为所有RouteControllers 的基类.

MainController=RouteController.extend({
  layoutTemplate:"mainLayout",
  // yield navbar and footer templates to navbar and footer regions respectively
  yieldTemplates:{
    "navbar":{
      to:"navbar"
    },
    "footer":{
      to:"footer"
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

接下来,您需要确保您的路由使用派生自的控制器MainController.

HomeController=MainController.extend({
  template:"home"
});

Router.map(function(){
  this.route("home",{
    path:"/",
    // optional, by default iron:router is smart enough to guess the controller name,
    // by camel-casing the route name and appending "Controller"
    controller:"HomeController"
  });
});
Run Code Online (Sandbox Code Playgroud)

所以现在你的家庭路由页面被一个带有"主页"类的div包围,所以你可以用普通的CSS设置它(或者更好,使用LESS):

.home-page{
  /* your css goes here */
}
Run Code Online (Sandbox Code Playgroud)

如果你定义了其他路由,这将无缝地工作,只需继承MainController,你就会自动拥有一个带有route-name-page类的页面.

当然,您可以为多个页面使用相同的样式,只需在CSS中指定它:

.home-page, .contact-page{
  /* your css goes here */
}
Run Code Online (Sandbox Code Playgroud)

你可以用布局做很好的事情,我非常鼓励使用它们.

  • 要添加到此方法:有时您需要更改主体类以使某个布局起作用.为此,使用所述布局的`rendered`和`destroyed`回调,即:`Template.layout.rendered = function(){$('body').addClass('layoutBody')};`然后`模板.layout.destroyed = function(){$('body').removeClass('layoutBody')};` (2认同)