2 回答
![?](http://img1.sycdn.imooc.com/545867790001599f02200220-100-100.jpg)
TA贡献1793条经验 获得超6个赞
如果您正在寻找专门的角度解决方案:
import {
Component,
OnInit,
HostListener,
ViewChild,
ElementRef,
} from "@angular/core";
@Component({
selector: "app-header",
templateUrl: "./header.component.html",
styleUrls: ["./header.component.scss"],
})
export class HeaderComponent implements OnInit {
currentWindowWidth: number;
isMobile: boolean;
@ViewChild("control") control: ElementRef;
constructor() {}
ngOnInit() {}
@HostListener("window:resize", ["$event"])
public onResize(window) {
this.isMobile = window.currentTarget.innerWidth < 993 ? true : false;
this.toggleMobileClasses(this.control.nativeElement, this.isMobile)
}
@HostListener("window:load", ["$event"])
public onLoad(window) {
this.isMobile = window.currentTarget.innerWidth < 993 ? true : false;
}
toggleMobileClasses(targetElement: HTMLElement, isMobile) {
isMobile ? targetElement.classList.add('text-center') : targetElement.classList.toggle('text-center');
}
}
HostListener 是这里的关键
声明要侦听的 DOM 事件并提供在该事件发生时运行的处理程序方法的装饰器。 Angular HostListener 文档
<div #control class="container">
<div class="row my-4">
<div class="col-md-12 d-flex justify-content-center">
<h2> EVALUACIÓN DE {{ curso }} </h2>
</div>
</div>
<div class="row">
<div class="col-md-9">
<h4>Pregunta 1 de 20 </h4>
<p>¿Cúal de las siguientes alternativas es correcta? </p>
</div>
<div class="col-md-3 d-flex align-items-center" id="icono-reloj">
<img class="mx-2" src="/assets/img/alarm-fill.svg" alt="" width="24" height="24" title="timer"> <span class="mx-3">0:20</span>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="list-group" ngFor="let alternativa of alternativas">
<p class="list-group-item list-group-item-action" (click)="avanzar()">este es un ejemplo de una alternativa ...</p>
</div>
</div>
</div>
</div>
此外,如果您将Angular Universalwindow is not defined用于 SSR,这种方法不会在服务器解析和填充动态 HTML 期间引发任何错误
![?](http://img1.sycdn.imooc.com/533e4d660001312002000200-100-100.jpg)
TA贡献1796条经验 获得超10个赞
function windowResizeFunc() {
function reportWindowSize() {
let h = window.innerHeight;
let w = window.innerWidth;
console.log("Current Width: "+ w);
if( w < 600 ) {
document.getElementById("yourElementId").classList.add("center");
} else {
document.getElementById("yourElementId").classList.remove("center");
}
}
window.onresize = reportWindowSize;
}
windowResizeFunc();
#yourElementId {
border: 1px solid #5599cc;
}
.center{
text-align: center;
}
<div id="yourElementId">Some text</div>
你可以使用 VanillaJS
添加回答
举报