TinyMCE v6图片插件宽高属性计算异常问题求助
解决TinyMCE 6图片插件读取样式宽高而非实际尺寸的问题
问题背景
编辑器内通过CSS设置大图片缩小显示,但编辑图片属性时,插件会从当前样式计算宽高并写入width/height属性,导致发布后图片保持缩小状态——我们需要让图片属性基于原始实际尺寸而非显示样式。
核心解决方案
替换TinyMCE默认的尺寸读取逻辑,改用图片的naturalWidth/naturalHeight属性(直接返回图片原始像素尺寸,不受CSS样式影响)。
方法1:修改图片对话框的尺寸填充逻辑
在编辑器初始化时,通过setup函数监听对话框打开事件,强制填充图片实际尺寸:
tinymce.init({ selector: 'textarea', plugins: 'image', toolbar: 'image', setup: (editor) => { editor.on('dialogopen', (e) => { // 只针对图片对话框操作 if (e.target.settings.name !== 'image') return; const selectedImg = editor.selection.getNode(); if (selectedImg.tagName !== 'IMG') return; // 获取图片原始尺寸 const actualWidth = selectedImg.naturalWidth; const actualHeight = selectedImg.naturalHeight; // 更新对话框中的宽高输入框 const dialog = e.target; dialog.find('#width').value(actualWidth); dialog.find('#height').value(actualHeight); }); } });
方法2:全局覆盖尺寸读取逻辑
如果需要更彻底的修改(比如避免保存时自动写入样式计算的尺寸),可以自定义插件拦截默认行为:
// 自定义插件:强制使用图片原始尺寸 tinymce.PluginManager.add('custom-image-dimensions', (editor) => { editor.on('BeforeExecCommand', (e) => { if (e.command !== 'mceImage') return; const selectedImg = editor.selection.getNode(); if (selectedImg.tagName !== 'IMG') return; // 直接获取原始尺寸,无需修改样式 const { naturalWidth: width, naturalHeight: height } = selectedImg; // 强制对话框使用原始尺寸 editor.settings.image_default_width = width; editor.settings.image_default_height = height; }); });
初始化编辑器时加载这个自定义插件:
tinymce.init({ selector: 'textarea', plugins: 'image custom-image-dimensions', toolbar: 'image' });
兼容老浏览器方案
如果需要支持IE8及以下(不支持naturalWidth),可以通过创建新Image对象加载原图获取尺寸:
function getOriginalImageSize(imgSrc) { return new Promise((resolve) => { const tempImg = new Image(); tempImg.onload = () => resolve({ width: tempImg.width, height: tempImg.height }); tempImg.src = imgSrc; }); } // 在对话框打开时调用 editor.on('dialogopen', async (e) => { if (e.target.settings.name !== 'image') return; const selectedImg = editor.selection.getNode(); if (selectedImg.tagName !== 'IMG') return; const { width, height } = await getOriginalImageSize(selectedImg.src); const dialog = e.target; dialog.find('#width').value(width); dialog.find('#height').value(height); });
内容的提问来源于stack exchange,提问作者Timur
相关产品推荐
相关产品推荐

