富文本返回的Html数据格式化

是这样的,有一个文章查看功能,流程是管理员在富文本编辑器里编写文章,将内容为html格式的数据传给后端,用户查看文章请求到html类型的数据格式时,不知道为啥,内容的图片和文字的样式非常乱

这时我们在使用v-html展示之前,做一些样式规范化处理,这里只处理图片,文字,表格,如果有其他的内容,可以增加处理

/**
 * 
 * 接收后端返回的html,用来规范图片与文字的展示
 * @param {*} rawHtml
 * 
 */

export default function normalizeHtml (rawHtml) {
  // 通过 DOMParser/临时容器处理服务端返回的 html,统一图片与段落样式
  if (!rawHtml) return ''
  const container = document.createElement('div')
  container.innerHTML = rawHtml

  // 规范图片:移除行内宽高,添加自适应类名
  const images = container.querySelectorAll('img')
  images.forEach(img => {
    img.removeAttribute('width')
    img.removeAttribute('height')
    img.style.width = ''
    img.style.height = ''
    img.style.maxWidth = '100%'
    img.style.height = 'auto'
    img.style.display = 'block'
    img.style.margin = '12px auto'
  })

  // 规范表格:允许横向滚动,避免溢出
  const tables = container.querySelectorAll('table')
  tables.forEach(tb => {
    tb.style.width = '100%'
    tb.style.borderCollapse = 'collapse'
    tb.style.tableLayout = 'fixed'
    tb.querySelectorAll('td,th').forEach(cell => {
      cell.style.wordBreak = 'break-word'
      cell.style.whiteSpace = 'normal'
    })
  })

  // 清理过度的内联 font/size 样式,统一文本行高与颜色
  const textBlocks = container.querySelectorAll('p, span, div, li')
  textBlocks.forEach(el => {
    el.style.backgroundColor=''
    el.style.lineHeight = ''
    el.style.margin='5px 0'
    el.style.fontSize = '17px'
    el.style.textAlign='left'
    el.style.color = ''
  })

  return container.innerHTML
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值