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

在HTML与WKWebView(Swift)中实现按钮点击后仅修改后续输入文本颜色

实现富文本式的文本颜色修改(仅改变后续输入文本颜色)

问题现状

点击颜色修改按钮时,原textarea内所有文本颜色都会被统一修改,需要实现类似富文本编辑器的效果:仅改变按钮按下后新输入文本的颜色。

核心思路

普通<textarea>是纯文本控件,仅支持全局统一样式,无法实现局部富文本效果。必须替换为contenteditable="true"的<div>,再通过浏览器原生富文本编辑API控制样式:

  • 使用document.execCommand('foreColor')命令,既可以修改选中文本的颜色,也能设置后续输入文本的默认颜色。

修改后的完整代码

HTML部分

<html>
<head>
    <meta charset="utf-8">
    <style>
        #editor {
          background-color: #000000;
          color: #666666;
          padding: 1em;
          border-radius: 10px;
          border: 2px solid transparent;
          outline: none;
          font-family: "Heebo", sans-serif;
          font-weight: 500;
          font-size: 16px;
          line-height: 1.4;
          width: 200px;
          height: 233px;
          overflow-y: auto;
        }
        
        #editor:hover {
          cursor: pointer;
          background-color: #eeeeee;
        }
        
        #editor:focus {
          cursor: text;
          color: #111111;
          background-color: #334455;
          border-color: #333333;
        }

        /* 为contenteditable元素实现placeholder效果 */
        #editor:empty:before {
          content: attr(placeholder);
          color: #666666;
          pointer-events: none;
        }
    </style>
</head>
<body>
    <!-- 替换textarea为支持富文本的可编辑div -->
    <div id="editor" contenteditable="true" placeholder="Enter a message..."></div>
    <script>
        function changeBackgroundColor(colorText) {
            document.body.style.background = colorText;
        }
        
        // 支持自定义颜色的文本样式设置函数
        function changeTextColor(color) {
            // 执行富文本命令:设置前景色(文本颜色)
            // 有选中文本则修改选中部分,无选中则设置后续输入的默认颜色
            document.execCommand('foreColor', false, color);
            // 重新聚焦编辑器,确保后续输入正常应用样式
            document.getElementById('editor').focus();
        }
    </script>
</body>
</html>

Swift(WKWebView调用部分)

// 调用时传入目标颜色值,示例为红色
webView.evaluateJavaScript("changeTextColor('#FF0000')", completionHandler: nil)

补充说明

  • document.execCommand兼容性极佳,适合简单富文本场景;如果需要更复杂的编辑逻辑,可以使用Range/Selection API手动处理选区样式。
  • 可编辑div的placeholder通过CSS伪元素实现,避免原生textarea的纯文本限制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 15:00:17