如何在TinyMCE 5编辑器中为插入的img标签自动添加rel属性
TinyMCE 5 自动给插入图片添加rel属性解决方案
image_rel_list 是TinyMCE为图片外层跳转链接提供的配置项,并不会作用于<img>标签本身,且默认编辑器会过滤<img>标签上的非标准属性rel,所以你之前的配置无法生效。
你可以按以下方式调整配置:
- 新增
extended_valid_elements配置,将rel加入<img>标签的允许属性白名单,避免被编辑器过滤 - 监听
BeforeSetContent事件,在图片插入到编辑器前自动追加属性
完整配置示例
tinyMCE.init({ selector: '#myTextarea', plugins: 'code image autolink link lists charmap print preview textcolor', toolbar: 'code image link | undo redo | insert | ', menubar: false, min_height: 300, // 允许img标签保留rel等自定义属性 extended_valid_elements: 'img[class|src|rel|width|height|alt|title]', setup: function (ed) { // 插入内容前自动处理img标签属性 ed.on('BeforeSetContent', function (e) { if (e.content.includes('<img')) { e.content = e.content.replace(/<img([^>]*)/gi, function(match, attrs) { // 自动添加rel="lightbox" if (!/rel=/.test(attrs)) { attrs += ' rel="lightbox"'; } // 自动追加imageborder类,保留原有class if (/class="([^"]*)"/.test(attrs)) { attrs = attrs.replace(/class="([^"]*)"/, 'class="$1 imageborder"'); } else { attrs += ' class="imageborder"'; } return `<img${attrs}`; }) } }); ed.on("keyup", function () { $('#preview').html(tinymce.activeEditor.getContent()); }); } });
调整后所有插入的图片都会自动生成你需要的HTML结构:
<img class="imageborder" src="https://xy.jpg" rel="lightbox" width="500" height="333" />
内容的提问来源于stack exchange,提问作者Berstos
相关产品推荐
相关产品推荐

