Angular 5中(window:resize)函数如何仅触发一次区间判断?
嘿,这个窗口resize频繁触发的问题我之前也碰到过,给你个实用的解决方案,核心就是跟踪当前区间状态 + 防抖处理,确保只有跨阈值的时候才触发一次判断:
实现思路
我们需要:
- 记录当前窗口所处的区间(是<=550px的移动端,还是>=551px的桌面端)
- 监听resize事件时,先判断新的区间,只有当区间发生变化时才执行你的判断逻辑
- 加上防抖,避免窗口调整过程中短时间内触发多次事件(可选但推荐)
具体代码实现(基于你的Angular 5组件)
首先在组件里引入必要的RxJS操作符(Angular 5对应RxJS 5.x版本,语法如下):
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Subscription } from 'rxjs/Subscription'; // 引入需要的RxJS操作符 import 'rxjs/add/observable/fromEvent'; import 'rxjs/add/operator/debounceTime'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit, OnDestroy { // 用于跟踪当前区间状态 private currentBreakpoint: 'mobile' | 'desktop'; // 保存resize事件的订阅,用于组件销毁时取消 private resizeSub: Subscription; ngOnInit() { // 初始化当前区间状态 this.currentBreakpoint = window.innerWidth <= 550 ? 'mobile' : 'desktop'; // 初始加载时触发一次(如果需要的话) this.handleBreakpointChange(this.currentBreakpoint); // 监听窗口resize事件 this.resizeSub = Observable.fromEvent(window, 'resize') // 防抖100ms,等待窗口尺寸稳定后再处理,可根据需求调整时间 .debounceTime(100) .subscribe(() => { const newBreakpoint = window.innerWidth <= 550 ? 'mobile' : 'desktop'; // 只有当区间发生变化时才执行逻辑 if (newBreakpoint !== this.currentBreakpoint) { this.currentBreakpoint = newBreakpoint; this.handleBreakpointChange(newBreakpoint); } }); } // 这里写你的判断逻辑 private handleBreakpointChange(breakpoint: 'mobile' | 'desktop') { // 根据区间返回对应的阈值 const triggerThreshold = breakpoint === 'mobile' ? 550 : 551; console.log(`触发判断,当前对应阈值:${triggerThreshold}px`); // 执行你需要的其他操作,比如更新视图、调用接口等 } // 组件销毁时取消订阅,避免内存泄漏 ngOnDestroy() { if (this.resizeSub) { this.resizeSub.unsubscribe(); } } }
关键细节说明
- 状态跟踪:
currentBreakpoint变量确保我们只在区间切换时触发逻辑,比如从551px缩小到550px时才触发,而中间的每一次尺寸变化都不会重复执行。 - 防抖处理:
debounceTime(100)能过滤掉窗口调整过程中的高频事件,只在用户停止调整100ms后再处理,减少不必要的计算开销。 - 内存泄漏防护:Angular组件销毁时一定要取消resize事件的订阅,否则会导致内存泄漏,影响应用性能。
这样调整后,不管你是把窗口从300px拉到700px,还是从800px缩到400px,都只会在跨越550px阈值的时候触发一次判断,完美符合你的需求!
内容的提问来源于stack exchange,提问作者Naturo Power
相关产品推荐
相关产品推荐

