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

如何使用Javascript将带样式属性的指定JSON动态转换为HTML DOM元素

实现方案

核心思路

你给出的JSON结构是类Quill Delta的富文本ops格式,转换逻辑很直接:

  • 遍历ops数组的每一项,对每个insert内容按attributes里的样式逐层包裹对应HTML标签
  • 样式嵌套顺序不影响最终显示效果,可自定义调整
  • 换行符\n可按需替换为<br>标签或者<p>段落标签

完整实现代码

// 你的目标JSON结构
const deltaJson = {"ops":[{"attributes":{"underline":true,"italic":true,"bold":true},"insert":"stackoverflow"},{"attributes":{"underline":true,"italic":true},"insert":" "},{"attributes":{"italic":true},"insert":"credit"},{"attributes":{"underline":true},"insert":"company"},{"insert":"\n"}]};

// 样式与HTML标签的映射关系,可按需修改
const tagMap = {
  bold: 'strong',
  italic: 'em',
  underline: 'u'
};

function opsToDom(ops) {
  // 用文档片段减少DOM重绘
  const fragment = document.createDocumentFragment();
  ops.forEach(op => {
    let content = op.insert;
    // 处理换行符
    if (content === '\n') {
      fragment.appendChild(document.createElement('br'));
      return;
    }
    // 先创建基础文本节点
    let node = document.createTextNode(content);
    // 存在样式就逐层嵌套对应标签
    if (op.attributes) {
      Object.keys(tagMap).forEach(style => {
        if (op.attributes[style]) {
          const tagEl = document.createElement(tagMap[style]);
          tagEl.appendChild(node);
          node = tagEl;
        }
      })
    }
    fragment.appendChild(node);
  })
  return fragment;
}

// 调用示例:将生成的DOM插入到页面指定容器
const targetContainer = document.querySelector('#your-target-element');
targetContainer.appendChild(opsToDom(deltaJson.ops));

转换效果说明

你给出的示例JSON运行后最终生成的DOM结构如下,完全还原原始带格式的文本:

<u><em><strong>stackoverflow</strong></em></u> <em>credit</em><u>company</u><br>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 16:06:03