假如this.html是富文本的内容 , 那么如下写法即可实现超出自适应
const tempDiv = document.createElement('div')
tempDiv.innerHTML = this.html
const images = tempDiv.querySelectorAll('img')
images.forEach((img) => {
img.style.maxWidth = '100%'
img.style.height = 'auto'
})
this.html = tempDiv.innerHTML
以vue为例使用el-form中的rules作为效验规则:
rules: {
html: [{ required: true, validator: checkRichText, trigger: 'blur' }]
}
在export default上方定义如下:
var checkRichText = (rule, value, callback) => {
if (value == '<p><br></p>' || value == '<p> </p>') {
callback(new Error('请输入内容'))
} else {
let str = value
.replace(/<[^<p>]+>/g, '')
.replace(/<[</p>$]+>/g, '')
.replace(/ /gi, '')
.replace(/<[^<br/>]+>/g, '')
.replace(/\s+/g, '')
if (!str.length) {
callback(new Error('请输入内容'))
} else {
callback() // 校验通过
}
}
}