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

为声明式创建的dijit/Editor添加onpaste事件无法触发,求助

解决dijit/Editor声明式创建时无法触发onPaste事件的问题

我之前也踩过dijit/Editor粘贴事件的坑,直接用data-dojo-attach-event或者data-dojo-props绑定onPaste确实没用——因为这个组件本身并没有把原生的paste事件封装成可直接绑定的组件事件,它的编辑内容是放在内部iframe里的,得换个思路处理:

方案一:通过onLoad事件绑定内部iframe的paste事件

编辑器初始化完成后,内部的iframe才会就绪,这时候我们可以拿到iframe的document对象,直接给它绑定原生paste事件。修改你的代码如下:

<div data-dojo-type="dijit/Editor" id="Editor1" name="Editor1Content" 
     data-dojo-props="extraPlugins: ['createLink','unlink','fontSize','foreColor','hiliteColor'], 
                      onChange:function(){MarkDocAsChanged();},
                      onLoad:function(){
                          // 获取编辑器内部的iframe文档对象
                          var editorDoc = this.editor.document;
                          // 绑定原生paste事件
                          editorDoc.addEventListener('paste', function(event) {
                              pasteAsPlainText(event);
                          });
                      }" >
    This is the current field content
</div>

注意在你的pasteAsPlainText函数里,一定要先调用event.preventDefault()阻止默认粘贴行为,再插入纯文本,比如:

function pasteAsPlainText(event) {
    event.preventDefault();
    // 获取剪贴板里的纯文本
    var plainText = event.clipboardData.getData('text/plain');
    // 插入到编辑器中
    dijit.byId('Editor1').execCommand('insertText', false, plainText);
}

方案二:自定义插件批量处理(适合多个编辑器的场景)

如果你的应用里有大量编辑器需要这个功能,写个自定义插件会更省心,不用每个编辑器都写重复的onLoad逻辑:

首先定义一个插件:

define([
    'dojo/_base/declare',
    'dijit/_editor/_Plugin'
], function(declare, _Plugin) {
    return declare(_Plugin, {
        initialize: function() {
            var editor = this.editor;
            var editorDoc = editor.document;
            // 绑定paste事件并处理为纯文本
            editorDoc.addEventListener('paste', function(event) {
                event.preventDefault();
                var plainText = event.clipboardData.getData('text/plain');
                editor.execCommand('insertText', false, plainText);
            });
        }
    });
});

然后在使用编辑器时,把这个插件加到extraPlugins里(假设插件的模块名是plugins/PlainTextPaste):

<div data-dojo-type="dijit/Editor" id="Editor1" name="Editor1Content" 
     data-dojo-props="extraPlugins: ['createLink','unlink','fontSize','foreColor','hiliteColor', 'plugins/PlainTextPaste'], 
                      onChange:function(){MarkDocAsChanged();}" >
    This is the current field content
</div>

为什么原来的方式无效?

dijit/Editor并没有将原生的paste事件包装成组件的onPaste事件,所以你用data-dojo-attach-event="onPaste:..."或者在props里定义onPaste函数,组件根本不会触发这个回调——必须直接操作内部iframe的DOM来绑定原生事件才行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:52:00