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

Angular13中Quill搭配quill-better-table自定义属性加载偏移问题

解决Quill + quill-better-table中Table自定义属性加载偏移问题

问题原因

quill-better-table默认的Table Blot未将自定义属性纳入允许列表,Quill在解析HTML时,会把未被当前Blot识别的属性转移到其他关联元素(如col标签),导致属性偏移。

解决方案

通过扩展quill-better-table的Table Blot,让它支持自定义属性的读取与写入:

1. 自定义Table Blot

创建扩展类,将自定义属性加入允许列表,并实现属性的解析和格式化逻辑:

import Quill from 'quill';
import QuillBetterTable from 'quill-better-table';

const TableBlot = QuillBetterTable.TableBlot;

class CustomTableBlot extends TableBlot {
  static blotName = 'better-table';
  static tagName = 'TABLE';
  // 继承原有允许属性,添加自定义属性
  static allowedAttributes = {
    ...TableBlot.allowedAttributes,
    'custom-attribute': true
  };

  // 从DOM节点读取属性值到Quill格式
  static formats(domNode: HTMLElement) {
    const formats = super.formats(domNode);
    const customAttrValue = domNode.getAttribute('custom-attribute');
    if (customAttrValue) {
      formats['custom-attribute'] = customAttrValue;
    }
    return formats;
  }

  // 将Quill格式应用到DOM节点
  format(name: string, value: any) {
    if (name === 'custom-attribute') {
      if (value) {
        this.domNode.setAttribute('custom-attribute', value);
      } else {
        this.domNode.removeAttribute('custom-attribute');
      }
      return;
    }
    super.format(name, value);
  }
}

// 注册自定义Blot,替换默认实现
Quill.register(CustomTableBlot, true);

2. 调整属性设置方式

避免直接操作DOM节点,改用Quill官方的format方法设置属性,确保格式被正确记录:

let tableModule: any = this.quill.getModule('better-table');
tableModule.insertTable(2, 2);
const [tableBlot] = tableModule.getTable();
// 针对Table Blot设置自定义属性
this.quill.format('custom-attribute', 'test', tableBlot);

3. 简化配置

由于自定义Table Blot已直接处理属性,可移除单独注册的Parchment Attributor,避免冲突:

// 移除以下代码
// const Parchment = Quill.import('parchment');
// const customAttribute = new Parchment.Attributor('custom-attribute', 'custom-attribute', {
//     scope: Parchment.Scope.BLOCK,
//     whitelist: ['test']
// });
// Quill.register(customAttribute);

验证效果

修改后,保存到数据库的HTML重新加载时,custom-attribute会保留在<table>标签上,不会被转移到col标签中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 13:28:19