【问题标题】:Angular2 - How to conditionally load css file in index.html?Angular2 - 如何有条件地在 index.html 中加载 css 文件?
【发布时间】:2017-10-30 23:51:48
【问题描述】:

我现在拥有的是 index.html 中带有深色主题的页面:

<base href="/">
<html>
<head>
    <title>XXX</title>
</head>
<body>
    <link rel="stylesheet" type="text/css" href="assets/dark_room.css">
    <my-app>Loading...</my-app>
</body>
</html>

我还有一个明亮的“light_room.css”主题需要实现,用户可以根据需要切换主题。我想知道我怎样才能做到这一点?

我认为这可以通过使用 url 参数来完成,这样当用户在 url 末尾键入 ?light_room=True 时,页面将加载 light_room.css。但是我认为它只能在普通模板中完成,而不能在 index.html 中完成。

有没有人有类似的在 index.html 中条件加载 css 文件的经验?

【问题讨论】:

  • 你试过这种方式吗?让您的后端根据 URL 参数生成不同的 index.html。
  • @Niklas 我认为这可能是一种方法,但我不知道如何。因为设置 URL 参数通常在 .ts 文件中完成,但 index.html 没有。

标签: javascript html css angular


【解决方案1】:

关键是主题通常只是一些不同的颜色。您可以将所有主题添加到一个 CSS 中。 my-app &gt; .dark 得到不同的颜色,类会在代码中动态添加。

这是一个更详细的示例,我如何使用它:

应用主题.scss:

@import '~@angular/material/theming';

@include mat-core();
$words-app-primary: mat-palette($mat-teal, 300);
$words-app-secondary: mat-palette($mat-indigo, 500);
$words-app-warn: mat-palette($mat-red, 500);

$words-app-theme: mat-light-theme($words-app-primary, $words-app-secondary, $words-app-warn);
@include angular-material-theme($words-app-theme);

app-words-root > md-sidenav-container.dark {
  $words-app-theme-dark: mat-dark-theme($words-app-primary, $words-app-secondary, $words-app-warn);
  @include angular-material-theme($words-app-theme-dark);
}

app.component.html:

<md-sidenav-container [class.dark]="useDarkTheme"> ... </md-sidenav-container>

非角度版本

app.component.js

import { DOCUMENT } from '@angular/platform-browser';

class AppComponent {
  constructor(@Inject(DOCUMENT) document: any) {
    let head  = document.getElementsByTagName('head')[0];
    let link  = document.createElement('link');
    link.rel  = 'stylesheet';
    link.type = 'text/css';
    link.href = 'assets/dark_room.css'; // you may want to get this from local storage or location
    head.appendChild(link);
  }
}

【讨论】:

  • 感谢您的回答,但我不允许触摸 css 文件,所以....我仍然需要找到一种方法以某种方式选择这两个文件
  • 这将是与标题类似的问题 - angular 2 在&lt;app&gt; 之外没有用于 dom 操作的功能。对于标题,他们提供Title 服务。但不适用于加载 css。
  • 是的,如果我可以包含功能,它可能是可行的。
  • 我想到我可以只创建2个index.html并在url之后加载index.html,但是当我输入“/index_light.html”时,页面总是显示“正在加载....”
猜你喜欢
  • 2017-08-07
  • 2015-01-05
  • 2014-05-03
  • 2015-01-31
  • 2016-05-18
  • 1970-01-01
  • 2018-02-24
  • 2020-05-23
  • 2021-11-24
相关资源
最近更新 更多