我想根据屏幕尺寸改变我类(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/