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

使用create-electron-app开发类Google Docs应用:textarea选中文字加粗实现问题

问题分析与解决方案

首先要明确:textarea是纯文本输入控件,无法为其中的部分文字单独设置样式,这就是你没法给选中文字加粗的核心原因。要实现类似Google Docs的富文本编辑功能,需要改用支持富文本的可编辑区域,比如带contenteditable属性的<div>。

修改后的代码实现

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Make word documents!</title>
    <link rel="stylesheet" href="index.css" />
    <style>
      .userInput {
        width: 100%;
        min-height: 300px;
        border: 1px solid #ccc;
        padding: 10px;
        font-size: 16px;
      }
    </style>
  </head>
  <body>
    <!-- 替换textarea为contenteditable的div -->
    <div class="userInput" contenteditable></div>

    <input type="button" value="Bold" onmousedown="bold()">

    <script>
      function bold() {
        // 使用document.execCommand对选中内容执行加粗操作
        document.execCommand('bold', false, null);
      }
    </script>
  </body>
</html>

关键说明

  1. 替换textarea:带contenteditable属性的div允许用户编辑内容,并且支持富文本格式(比如加粗、斜体等)。
  2. execCommand用法:document.execCommand('bold')会直接切换选中内容的加粗状态——如果选中文字未加粗则添加加粗样式,已加粗则移除。这个API在Electron环境中完全可用,因为Electron基于Chromium内核,对该API的支持很稳定。
  3. 原代码中getSelectedText()返回的是字符串,不是DOM元素,所以无法通过style.fontWeight设置样式,这也是你之前尝试失败的原因。改用富文本编辑区域后,不需要手动处理选中的文本内容,直接用execCommand即可完成格式操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 05:37:07