如何在TinyMCE中从不可编辑元素执行JavaScript函数?
TinyMCE不可编辑区域按钮触发事件解决方案
TinyMCE支持给不可编辑区域内的按钮绑定点击事件,但直接使用onclick="myFunction()"无法触发——核心原因是编辑器内容运行在独立的iframe上下文里,主页面定义的全局函数不在这个iframe的作用域范围内,导致按钮找不到对应函数。
下面提供两种可行的解决方法:
方法一:使用事件委托监听点击
通过TinyMCE的setup配置项,在编辑器初始化后给内容区文档添加事件委托,统一处理按钮点击:
tinymce.init({ selector: 'textarea#tinymce', height: 500, content_style: ` body { font-family:Helvetica,Arial,sans-serif; font-size:16px } .myclass { border: 0.1rem solid green; border-radius: 0.8rem; padding: 0.2rem; } .non-editable { border-color: red; } `, noneditable_class: 'non-editable', setup: function(editor) { editor.on('init', function() { const doc = editor.getDoc(); doc.addEventListener('click', function(e) { // 判断点击目标为按钮时触发逻辑 if (e.target.tagName === 'BUTTON') { console.log("Hello world"); } }); }); } });
这种方式无需修改原有按钮的onclick属性,所有区域的按钮点击都会被监听处理。
方法二:将函数注入到iframe上下文
把目标函数挂载到编辑器iframe的window对象上,让按钮的onclick能找到对应函数:
tinymce.init({ selector: 'textarea#tinymce', height: 500, content_style: ` body { font-family:Helvetica,Arial,sans-serif; font-size:16px } .myclass { border: 0.1rem solid green; border-radius: 0.8rem; padding: 0.2rem; } .non-editable { border-color: red; } `, noneditable_class: 'non-editable', setup: function(editor) { editor.on('init', function() { const win = editor.getWin(); // 将函数注入到iframe的window作用域 win.myFunction = function() { console.log("Hello world"); }; }); } });
配置完成后,原有按钮的onclick="myFunction()"就能正常触发控制台输出。
内容的提问来源于stack exchange,提问作者user19691966
相关产品推荐
相关产品推荐

