You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SPFx代码中识别Web部件是否处于全屏宽度模式

识别SPFx Web部件是否处于全屏宽度模式(SPFx 1.15.2)

针对SPFx 1.15.2版本,判断Web部件是否处于全屏宽度模式(full bleed)最可靠的方式是依赖SharePoint原生的DOM类标记,而非通过元素宽度计算,具体实现如下:

核心判断逻辑

SharePoint会给处于全屏模式的Canvas Section添加CanvasSection--fullWidth类,我们可以通过Web部件的根DOM元素向上查找该容器来确认模式:

// 在Web部件类中实现判断方法
private isFullBleedActive(): boolean {
  // 从Web部件根元素向上匹配全屏Section容器
  const fullWidthSection = this.context.domElement.closest('.CanvasSection--fullWidth');
  return !!fullWidthSection;
}

实时监听模式切换

如果需要在用户切换全屏/普通模式时自动调整样式,可通过MutationObserver监听Canvas Section的类变化:

private sectionObserver: MutationObserver | undefined;

protected onInit(): Promise<void> {
  return super.onInit().then(() => {
    // 定位Web部件所在的Canvas Section
    const parentSection = this.context.domElement.closest('.CanvasSection');
    if (parentSection) {
      // 监听Section的类属性变化
      this.sectionObserver = new MutationObserver(mutations => {
        mutations.forEach(mutation => {
          if (mutation.attributeName === 'class') {
            const isFullBleed = this.isFullBleedActive();
            // 执行样式更新逻辑
            this.applyModeStyles(isFullBleed);
          }
        });
      });

      this.sectionObserver.observe(parentSection, { attributes: true });
    }
    return Promise.resolve();
  });
}

protected onDispose(): void {
  // 销毁观察者,避免内存泄漏
  if (this.sectionObserver) {
    this.sectionObserver.disconnect();
    this.sectionObserver = undefined;
  }
  super.onDispose();
}

private applyModeStyles(isFullBleed: boolean): void {
  // 给Web部件根元素添加/移除全屏样式类
  const rootElement = this.context.domElement;
  if (isFullBleed) {
    rootElement.classList.add('webpart-fullbleed');
  } else {
    rootElement.classList.remove('webpart-fullbleed');
  }
}

对应样式示例

在Web部件的SCSS文件中定义全屏模式下的样式:

.webpart-fullbleed {
  padding: 0;
  max-width: 100vw;
  width: 100vw;
  margin-left: calc(-50vw + 50%);
}

关键注意点

  • 避免通过元素宽度判断:移动端、窗口缩放场景下,普通模式的宽度可能和全屏模式重叠,导致判断失效。
  • 必须清理观察者:在Web部件销毁时断开MutationObserver,防止内存泄漏。
  • 原生类的稳定性:CanvasSection--fullWidth是SharePoint官方用于标记全屏Section的类,在SPFx 1.15.2版本中是稳定的,不会随意变更。

内容的提问来源于stack exchange,提问作者Martin Bielik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 14:25:18