Vue中TinyMCE表格创建对话框如何限制最大宽度为100%
限制TinyMCE表格创建对话框的最大宽度为100%
方法1:修改原生表格对话框的输入验证
在TinyMCE的初始化配置中,通过setup钩子监听对话框打开事件,针对表格创建对话框的宽度输入框添加限制逻辑:
init: { table_grid: false, // 其他配置... setup: (editor) => { editor.on('dialogopen', (e) => { // 仅处理表格创建对话框 if (e.target.settings.name === 'table') { const widthInput = e.target.find('#width')[0]; if (widthInput) { // 输入值变化时自动修正超过100%的内容 widthInput.on('change', () => { const rawValue = widthInput.value(); if (!rawValue) return; const numValue = parseFloat(rawValue.replace('%', '')); if (!isNaN(numValue) && numValue > 100) { widthInput.value('100%'); } }); // 限制输入字符,仅允许数字、%和控制键 widthInput.on('keydown', (evt) => { const allowedControlKeys = [8, 9, 13, 37, 39, 46]; // 退格、Tab、回车、方向键、删除 const key = evt.key; if (!(/[0-9%]/.test(key) || allowedControlKeys.includes(evt.keyCode))) { evt.preventDefault(); } }); } } }); } }
这段代码会在用户打开表格创建对话框时,自动给宽度输入框加上校验:输入超过100%的数值会被自动修正为100%,同时禁止输入数字和%以外的无效字符。
方法2:自定义表格插入对话框(完全自主控制)
如果需要更灵活的自定义(比如调整对话框布局、添加额外提示),可以直接替换原生的插入表格功能:
init: { table_grid: false, toolbar: 'custominserttable', // 替换原生的inserttable按钮 // 其他配置... setup: (editor) => { // 移除原生的插入表格按钮和菜单项 editor.ui.registry.removeMenuItem('inserttable'); editor.ui.registry.removeButton('inserttable'); // 添加自定义插入表格按钮 editor.ui.registry.addButton('custominserttable', { text: '插入表格', onAction: () => { editor.windowManager.open({ title: '插入表格', body: { type: 'panel', items: [ { type: 'input', name: 'rows', label: '行数', inputMode: 'numeric', value: '2' }, { type: 'input', name: 'cols', label: '列数', inputMode: 'numeric', value: '2' }, { type: 'input', name: 'width', label: '宽度(最大100%)', placeholder: '例如:80%' } ] }, buttons: [ { type: 'cancel', text: '取消' }, { type: 'submit', text: '插入', primary: true } ], onSubmit: (api) => { const data = api.getData(); // 处理宽度参数,强制限制在100%以内 let width = data.width?.trim(); if (width) { const numVal = parseFloat(width.replace('%', '')); if (!isNaN(numVal)) { width = numVal > 100 ? '100%' : `${numVal}%`; } else { width = '100%'; // 无效输入默认设为100% } } // 生成表格HTML并插入 const rowHtml = Array.from({ length: parseInt(data.rows) || 2 }) .map(() => `<tr>${Array.from({ length: parseInt(data.cols) || 2 }).map(() => '<td> </td>').join('')}</tr>`) .join(''); const tableHtml = `<table${width ? ` width="${width}"` : ''}><tbody>${rowHtml}</tbody></table>`; editor.insertContent(tableHtml); api.close(); } }); } }); } }
这种方式完全替换了原生对话框,你可以自由调整输入项的提示、默认值,甚至添加额外的配置项,从根源上确保表格宽度不会超出100%。
方案对比
- 方法1侵入性低,基于原生对话框修改,适合快速实现需求;
- 方法2灵活性更高,适合需要自定义对话框样式或添加额外逻辑的场景;
- 两种方案都能避免用户设置超出编辑器范围的表格宽度,比事后用CSS修正更高效。
内容的提问来源于stack exchange,提问作者user1766169
相关产品推荐
相关产品推荐

