处理html显示
处理html显示,主要是编辑器保存后展示的处理
编码处理-基础
export function decodeHTMLEntities(text) {
if (!text) return ''
const entities = {
' ': ' ',
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': "'",
''': "'",
'©': '©',
'®': '®',
'™': '™',
'…': '…',
'—': '—',
'–': '–',
'‘': '\'',
'’': '\'',
'“': '"',
'”': '"'
}
return text.replace(/&[a-zA-Z0-9#]+;/g, function(match) {
return entities[match] || match
})
}
图片处理
export function extractImagesFromHtml(html, { placeholder = '[[IMG_{i}]]', remove = true } = {}) {
const doc = new DOMParser().parseFromString(html || '', 'text/html')
const images = []
const nodeList = Array.from(doc.body.querySelectorAll('img'))
nodeList.forEach((img, i) => {
const data = {
index: i,
src: img.getAttribute('src') || '',
alt: img.getAttribute('alt') || '',
title: img.getAttribute('title') || '',
width: img.getAttribute('width') || '',
height: img.getAttribute('height') || '',
style: img.getAttribute('style') || '',
attrs: Array.from(img.attributes).reduce((m, a) => {
m[a.name] = a.value
return m
}, {})
}
images.push(data)
if (remove) {
img.remove()
} else {
const span = doc.createElement('span')
span.textContent = placeholder.replace('{i}', i) // [[IMG_0]]
img.replaceWith(span)
}
})
return { html: doc.body.innerHTML, images }
}
使用
this.text=extractImagesFromHtml(decodeHTMLEntities(html))
<p v-html="text.html"></p>
<div class="html-imgs">
<el-image v-for="item in text.images" :key="item.index" :src="item.src" :preview-src-list="[item.src]">
</el-image>
</div>
本文来自博客园,作者:流云君,转载请注明原文链接:https://www.cnblogs.com/yun10011/p/19062197

浙公网安备 33010602011771号