是这样的,有一个文章查看功能,流程是管理员在富文本编辑器里编写文章,将内容为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
}
1万+

被折叠的 条评论
为什么被折叠?



