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

Angular中如何实现客户自定义添加与选择字体的功能

Angular 实现客户字体选择与自定义添加功能

一、基础字体选择功能实现

1. 核心逻辑实现

在组件中定义内置字体列表,通过下拉选择器让用户切换字体,并实时应用到目标内容:

// font-selector.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-font-selector',
  templateUrl: './font-selector.component.html',
  styleUrls: ['./font-selector.component.css']
})
export class FontSelectorComponent {
  // 内置常用字体列表
  availableFonts = [
    { name: 'Arial', value: 'Arial, sans-serif' },
    { name: 'Times New Roman', value: '"Times New Roman", serif' },
    { name: 'Courier New', value: '"Courier New", monospace' },
    { name: 'Verdana', value: 'Verdana, sans-serif' },
    { name: 'Georgia', value: 'Georgia, serif' }
  ];
  selectedFont = this.availableFonts[0].value; // 默认选中第一个字体

  // 字体选择变更事件
  onFontChange(event: Event) {
    const target = event.target as HTMLSelectElement;
    this.selectedFont = target.value;
    this.applyFontToContent();
  }

  // 将选中字体应用到目标内容
  applyFontToContent() {
    const contentElement = document.getElementById('target-content');
    if (contentElement) {
      contentElement.style.fontFamily = this.selectedFont;
    }
  }
}

2. 模板与样式配置

编写模板渲染下拉选择器和示例内容,并优化选项显示样式:

<!-- font-selector.component.html -->
<div class="font-selector">
  <label for="font-picker">选择字体:</label>
  <select id="font-picker" (change)="onFontChange($event)" [value]="selectedFont">
    <option *ngFor="let font of availableFonts" 
            [value]="font.value" 
            [style.--font-family]="font.value">
      {{ font.name }}
    </option>
  </select>
</div>

<!-- 应用字体的目标内容区域 -->
<div id="target-content" [style.fontFamily]="selectedFont">
  这是应用选中字体的示例文本
</div>
/* font-selector.component.css */
.font-selector {
  margin: 20px 0;
}

select#font-picker option {
  font-family: var(--font-family);
}

二、支持自定义字体添加的扩展功能

1. 扩展组件逻辑

添加自定义字体的输入、加载验证和列表添加功能:

// font-selector.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-font-selector',
  templateUrl: './font-selector.component.html',
  styleUrls: ['./font-selector.component.css']
})
export class FontSelectorComponent {
  availableFonts = [
    { name: 'Arial', value: 'Arial, sans-serif' },
    { name: 'Times New Roman', value: '"Times New Roman", serif' },
    { name: 'Courier New', value: '"Courier New", monospace' },
    { name: 'Verdana', value: 'Verdana, sans-serif' },
    { name: 'Georgia', value: 'Georgia, serif' }
  ];
  selectedFont = this.availableFonts[0].value;
  customFontName = '';
  customFontUrl = '';

  onFontChange(event: Event) {
    const target = event.target as HTMLSelectElement;
    this.selectedFont = target.value;
    this.applyFontToContent();
  }

  applyFontToContent() {
    const contentElement = document.getElementById('target-content');
    if (contentElement) {
      contentElement.style.fontFamily = this.selectedFont;
    }
  }

  // 添加并加载自定义字体
  addCustomFont() {
    if (!this.customFontName.trim() || !this.customFontUrl.trim()) {
      alert('请填写完整的字体名称和URL');
      return;
    }

    // 加载并验证字体文件
    const fontFace = new FontFace(this.customFontName, `url(${this.customFontUrl})`);
    fontFace.load().then(() => {
      // 字体加载成功后添加到系统字体库和可选列表
      document.fonts.add(fontFace);
      const fontValue = `"${this.customFontName}", sans-serif`;
      this.availableFonts.push({ name: this.customFontName, value: fontValue });
      // 自动选中新添加的字体
      this.selectedFont = fontValue;
      this.applyFontToContent();
      // 清空输入框
      this.customFontName = '';
      this.customFontUrl = '';
    }).catch((error) => {
      alert(`字体加载失败:${error.message}`);
    });
  }
}

2. 更新模板添加自定义字体输入区

<!-- font-selector.component.html -->
<div class="font-selector">
  <label for="font-picker">选择字体:</label>
  <select id="font-picker" (change)="onFontChange($event)" [value]="selectedFont">
    <option *ngFor="let font of availableFonts" 
            [value]="font.value" 
            [style.--font-family]="font.value">
      {{ font.name }}
    </option>
  </select>
</div>

<!-- 自定义字体添加模块 -->
<div class="custom-font-add">
  <h3>添加自定义字体</h3>
  <div>
    <label for="font-name">字体名称:</label>
    <input id="font-name" [(ngModel)]="customFontName" placeholder="例如:MyCustomFont">
  </div>
  <div>
    <label for="font-url">字体文件URL:</label>
    <input id="font-url" [(ngModel)]="customFontUrl" placeholder="例如:/assets/fonts/myfont.ttf">
  </div>
  <button (click)="addCustomFont()">添加字体</button>
</div>

<div id="target-content" [style.fontFamily]="selectedFont">
  这是应用选中字体的示例文本
</div>

3. 样式优化

/* font-selector.component.css */
.font-selector {
  margin: 20px 0;
}

select#font-picker option {
  font-family: var(--font-family);
}

.custom-font-add {
  margin-top: 30px;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.custom-font-add div {
  margin: 10px 0;
}

.custom-font-add input {
  margin-left: 10px;
  padding: 5px;
  width: 300px;
}

关键注意点

  • 外部字体URL需满足跨域要求,服务器需配置CORS允许访问
  • 推荐使用WOFF2格式字体以获得更好的加载性能
  • 可扩展支持本地字体上传,通过FileReader将文件转换为DataURL后加载

内容的提问来源于stack exchange,提问作者Zhi Kai TeØ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 15:35:50