微信小程序<rich-view>中&nbsp不缩进问题解决方案

1,199 阅读1分钟

<rich-text>图片样式和文字缩进问题

<rich-text nodes="{{content}}"></rich-text>

//content内容
'<p>&nbsp; &nbsp; &nbsp; &nbsp; 我是段落1</p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; 我是段落2</p>
<p><img src="https://test1.image" alt="" width="1440" height="1080" /></p>
<p>&nbsp; &nbsp; &nbsp; &nbsp;我是段落3</p>
<p><img src="https://test2.image" alt="" width="1440" height="1080" /></p>
<p><img src="https://test3.image" alt="" width="1015" height="571" /></p>'

但是小程序&nbsp并不生效,没有缩进效果。 content.replace(/&nbsp;/g,"\xa0")即可解决问题

最终代码为:

//重置img样式 、缩进p标签
resetCss: function (content) {
  let reg = /(style|class)="[^"]+"/gi;
  let img = /<img[^>]+>/gi;
  let res;
  // 去掉img原始样式
  if (img.test(content)) {
    res = content.match(img);
    for (let i = 0; i < res.length; i++) {
      content = content.replace(res[i], res[i].replace(reg, ""));
    }
  }
  
  // 设置img样式、设置缩进
  return content
  .replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block"')
  .replace(/&nbsp;/g,"\xa0")
},