在Angular中,媒体查询可能不起作用的原因有很多,以下是一些解决方法的示例代码:
@media screen and (max-width: 600px) {
.my-element {
/* 样式 */
}
}
@HostBinding
装饰器将媒体查询应用于组件:import { Component, HostBinding } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent {
@HostBinding('class.my-element')
get isMobile() {
return window.innerWidth < 600;
}
}
Renderer2
来动态应用媒体查询:import { Component, Renderer2, OnInit } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements OnInit {
constructor(private renderer: Renderer2) {}
ngOnInit() {
const mediaQuery = this.renderer.createElement('style');
this.renderer.appendChild(mediaQuery, this.renderer.createText(`
@media screen and (max-width: 600px) {
.my-element {
/* 样式 */
}
}
`));
this.renderer.appendChild(document.head, mediaQuery);
}
}
这些示例代码可以帮助您解决在Angular中媒体查询不起作用的问题。根据您的具体情况,您可能需要根据自己的需求进行相应的调整。