如何在 Angular 中使用不同的样式表支持不同的屏幕尺寸?

How can I support different screen sizes with different stylesheets in Angular?

我正在使用 Angular 5,目前正在制作页眉,当我将屏幕调整为移动分辨率时,设计变得非常难看。我的想法是制作两种不同的样式表,一种用于移动设备,一种用于 PC,如下所示:

<link rel="stylesheet" media="screen and (min-device-width: 800px)" href="800.css" />

这是解决问题的明智方法吗?如果没有,请给我一个替代方案。

除此之外,我应该把样式表 link 放在 Angular 的什么地方?通常它放在 index.html 但在 Angular 中样式列在 component.ts 文件中,这里我不能做 the media="screen and (min-device-width: 800px)" 部分,所以我该如何解决这个问题?

在您的 .angular-cli.json 文件中,您应该向 apps.styles 数组添加一个字符串。

例如,当您的 mobile.csstablet.css 位于 app 文件夹中时,只需添加:mobile.csstablet.css
当样式驻留在例如 styles 文件夹(在 app 内)时,添加:styles/yourstyle.css

根据您的 css 文件添加媒体查询。

@media only screen and (max-width: 500px) {
    body {
        background-color: lightblue;
    }
}

您不需要在 index.html 中添加样式链接。

如果我没听错,您只想为移动设备加载所需的 css 而不是加载所有内容(也包括桌面设备),对吗? 如果是这样,您必须在 index.html

中定义一个脚本
<script>
    var deviceWidth = window.orientation == 0 ? window.screen.width : window.screen.height;
    //use this if you want to check it is really a mobile device.
    var isAndroid = navigator.userAgent.indexOf('Android') >= 0 && window.devicePixelRatio;

    var cssHref = deviceWidth > 800 ? "app_desktop.css" : "app_mobile.css";
    var linkElement = document.createElement("link");
    linkElement.setAttribute("rel",  "stylesheet");
    linkElement.setAttribute("type",  "text/css");
    linkElement.setAttribute("href",  cssHref);
<script>

这不会响应,它只会工作一次。它也没有经过测试,所以它不会按预期工作:)