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

如何在类Google Docs编辑器中实现用户修改字体大小功能

实现选中文本自定义字体大小的方案

下面提供两种适配你现有编辑器代码的实现方式,解决自定义字体大小的问题:

方法一:使用document.execCommand快速实现

execCommand的fontSize命令支持自定义CSS单位(如px、em),但需要先启用styleWithCSS模式,避免生成过时的<font>标签。

步骤1:添加HTML控件

在原有控件后添加字体大小输入框和设置按钮:

<!-- 字体大小控件 -->
<input type="number" id="fontSizeInput" placeholder="字体大小(px)" min="8" max="72">
<button onclick="changeFontSize()">设置字体大小</button>

步骤2:添加JavaScript处理函数

在原有脚本中加入以下函数:

const changeFontSize = () => {
  const fontSize = document.getElementById('fontSizeInput').value;
  // 校验输入合法性
  if (!fontSize || isNaN(Number(fontSize))) {
    alert('请输入有效的数字');
    return;
  }
  
  // 启用CSS样式模式,确保生成内联样式而非<font>标签
  document.execCommand("styleWithCSS", false, true);
  // 执行字体大小设置,参数带单位
  document.execCommand("fontSize", false, `${fontSize}px`);
};

方法二:手动操作Range和DOM(更灵活)

如果需要更精细的控制(比如避免嵌套过多span),可以像你实现高亮功能那样,直接操作选中范围并包裹自定义样式的span:

替换上述changeFontSize函数为:

const changeFontSize = () => {
  const fontSize = document.getElementById('fontSizeInput').value;
  if (!fontSize || isNaN(Number(fontSize))) {
    alert('请输入有效的数字');
    return;
  }

  const selection = window.getSelection();
  if (selection.rangeCount === 0) return;

  const range = selection.getRangeAt(0);
  // 检查是否选中了整个元素,直接修改元素样式
  if (range.startContainer === range.endContainer 
      && range.startOffset === 0 
      && range.endOffset === range.startContainer.length) {
    range.startContainer.parentElement.style.fontSize = `${fontSize}px`;
  } else {
    // 创建带字体大小样式的span
    const span = document.createElement('span');
    span.style.fontSize = `${fontSize}px`;
    // 将选中内容移入span并插入回文档
    span.appendChild(range.extractContents());
    range.insertNode(span);
    // 恢复选中状态
    selection.removeAllRanges();
    selection.addRange(range);
  }
};

完整修改后的代码

将上述修改整合到你的原代码中,最终代码如下:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Editor</title>
    <link rel="stylesheet" href="index.css" />
  </head>
  <body>
    <button class="bold" onclick="document.execCommand('bold',false,null);">
      𝗕
    </button>

    <button class="italic" onclick="document.execCommand('italic',false,null);">
      𝘐
    </button>

    <button
      class="underline"
      onclick="document.execCommand('underline',false,null);"
    >
      U̲
    </button>

    <input
      type="color"
      class="color-picker"
      id="colorPicker"
      oninput="changeColorText(this.value);"
    />
    <label>Select color</label>

    <button id="highlight"><mark>Highlight</mark></button>

    <!-- 新增字体大小控件 -->
    <input type="number" id="fontSizeInput" placeholder="字体大小(px)" min="8" max="72">
    <button onclick="changeFontSize()">设置字体大小</button>

    <fieldset class="userInput" contenteditable="true"></fieldset>

    <script>
      var boldBtn = document.querySelector(".bold");
      var italicBtn = document.querySelector(".italic");
      var underlineBtn = document.querySelector(".underline");
      var colorPicker = document.querySelector(".color-picker");
      var highlightBtn = document.querySelector("#highlight");

      boldBtn.addEventListener("click", function () {
        boldBtn.classList.toggle("inUse");
      });

      italicBtn.addEventListener("click", function () {
        italicBtn.classList.toggle("inUse");
      });

      underlineBtn.addEventListener("click", function () {
        underlineBtn.classList.toggle("inUse");
      });

      highlightBtn.addEventListener("click", function () {
        highlightBtn.classList.toggle("inUse");
      });

      const changeColorText = (color) => {
        document.execCommand("styleWithCSS", false, true);
        document.execCommand("foreColor", false, color);
      };

      document
        .getElementById("highlight")
        .addEventListener("click", function () {
          var range = window.getSelection().getRangeAt(0),
            span = document.createElement("span");

          span.className = "highlight";
          span.appendChild(range.extractContents());
          range.insertNode(span);
        });

      // 新增字体大小设置函数
      const changeFontSize = () => {
        const fontSize = document.getElementById('fontSizeInput').value;
        if (!fontSize || isNaN(Number(fontSize))) {
          alert('请输入有效的数字');
          return;
        }
        
        document.execCommand("styleWithCSS", false, true);
        document.execCommand("fontSize", false, `${fontSize}px`);
      };
    </script>
  </body>
</html>

常见问题说明

  • 之前用变量失败可能是因为未启用styleWithCSS,导致execCommand生成的是<font size="x">标签(仅支持1-7的数字),而非自定义单位的CSS样式。
  • 输入校验可以避免无效值导致的样式错误,根据需求可调整提示方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 13:36:14