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

Blazor中使用JSInterop实现富文本编辑器的OnClick问题求助

问题分析与解决方案

问题根源

你的代码存在三个核心问题:

  1. 首次点击需两次生效:每次点击Blazor按钮时,都会调用buttonPressed函数给所有按钮重复绑定JS点击事件。第一次点击只是完成事件绑定,并没有执行富文本命令;第二次点击才会触发刚绑定的JS事件,执行document.execCommand。
  2. 多次弹窗/命令重复执行:每次点击都会新增一次事件绑定,点击次数越多,按钮上绑定的click事件就越多,触发时就会多次执行弹窗和命令逻辑。
  3. 图片无法插入:执行insertImage前没有确保编辑区域获得焦点,导致命令无法作用于目标区域。

修复后的代码实现

1. Blazor组件代码(HTML部分)

修改按钮的@onclick逻辑,直接把当前按钮的命令名称传给JS方法:

<div class="main-content">
    <!--Text Editor Header-->
    <div class="text-editor-header">
        <button @onclick="() => ExecuteCommand("bold")" type="button" class="btn">
            <i class="fa fa-bold"></i>
        </button>
        <button @onclick="() => ExecuteCommand("justifyFull")" type="button" class="btn">
            <span class="fa fa-align-justify"></span>
        </button>
        <button @onclick="() => ExecuteCommand("insertImage")" type="button" class="btn">
            <span class="fa fa-image"></span>
        </button>
    </div>
    <div class="content" id="content" contenteditable="true"></div>
</div>

2. C#代码

更新方法,直接将命令名称作为参数传递给JS:

async Task ExecuteCommand(string command)
{
    await JsRuntime.InvokeVoidAsync("executeRichTextCommand", command);
}

3. JSInterop代码

移除重复的事件绑定逻辑,直接执行富文本命令,同时确保编辑区域获得焦点:

function executeRichTextCommand(command) {
    // 先让编辑区域获得焦点,确保命令能作用于目标区域
    const editor = document.getElementById('content');
    editor.focus();

    if (command === 'createLink' || command === 'insertImage') {
        let url = prompt('Enter the link here:', 'http://');
        // 仅当用户输入有效URL时执行命令
        if (url && url !== 'http://') {
            document.execCommand(command, false, url);
        }
    } else {
        document.execCommand(command, false, null);
    }
}

额外优化建议

  • 组件初始化时可以自动让编辑区域获得焦点,提升用户操作流畅度。
  • document.execCommand已被标记为废弃API,长期维护可以考虑使用Range/Selection原生API实现富文本操作,或者选用开源的Blazor富文本组件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 05:25:13