html - 风格的动态变化

标签 html css angular typescript

我想根据屏幕尺寸改变我类(class)的风格,像这样

<p [ngStyle]="{'color': isMobile() ? 'red' : 'blue'}">Lorem Ipsum</p>

这段代码是在我的component.ts中调用方法

 isMobile() {      
    return window.innerWidth < 640;
 }

但据我所知,只有在我点击窗口某处时才会调用此函数,而不是在调整大小时调用。我怎样才能让它立即发生?

最佳答案

您可以使用如下媒体查询 (Sass):

.color-size {
  color: blue;
  @media screen and (max-width: 640px) {
    color: red;
  }
}

或纯CSS:

.color-size {
  color: blue;
}
@media screen and (max-width: 640px) {
  .color-size {
    color: red;
  }
}

如果你想通过ts中的事件来做:

  isMobile: boolean;
  @HostListener('window:resize', ['$event'])
  onResize(event) {
    if (event.target.innerWidth < 640) {
      this.isMobile = true;
    } else {
      this.isMobile = false;
    }
  }

模板将是:

<p (window:resize)="onResize($event)" [ngStyle]="{ color: isMobile ? 'red' : 'blue' }">Lorem Ipsum</p>

关于html - 风格的动态变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55996203/

相关文章:

html - 类级别的动态CSS

php - 根据链接将表单数据提交到各个位置

javascript - 如何将ajax成功数据的值显示到html表格中?

html - DIV 上的第一个 child 选择不起作用

database - 如何检索数据并将其存储到数据库中?

javascript - 合并两个 observables,单一输出

javascript - 使用 jquery mobile 和 codeigniter 框架 php

javascript - 如何更改已经显示的 Bootstrap 弹出窗口的内容?

css - 加载另一个页面时链接移动的导航问题

Angular 在一个组件中提供多种服务