guhongwei 3 years ago
parent
commit
4b73f14906
2 changed files with 32 additions and 1 deletions
  1. 4 1
      pages/news/detail.js
  2. 28 0
      utils/wangeditor.js

+ 4 - 1
pages/news/detail.js

@@ -1,5 +1,6 @@
 // pages/home/index.js
 const app = getApp()
+import { formatRichText } from '../../utils/wangeditor';
 Page({
 
   /**
@@ -30,7 +31,9 @@ Page({
       header: { 'x-tenant': app.globalData.tenant },
       data: {},
       success: res => {
-        this.setData({ detailInfo: res.data.data })
+        var result = res.data.data;
+        result.content = formatRichText(result.content)
+        this.setData({ detailInfo: result })
       },
       error: err => {
         wx.showToast({

+ 28 - 0
utils/wangeditor.js

@@ -0,0 +1,28 @@
+/**
+ * 处理富文本里的图片宽度自适应
+ * 1.去掉img标签里的style、width、height属性
+ * 2.img标签添加style属性:max-width:100%;height:auto
+ * 3.修改所有style里的width属性为max-width:100%
+ * 4.去掉<br/>标签
+ * @param html
+ * @returns {void|string|*}
+ */
+function formatRichText(html) {
+  let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
+    match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
+    match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
+    match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
+    return match;
+  });
+  newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
+    match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
+    return match;
+  });
+  newContent = newContent.replace(/<br[^>]*\/>/gi, '');
+  newContent = newContent.replace(/\<img/gi, '< img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:10px;"');
+  return newContent;
+}
+
+module.exports = {
+  formatRichText
+}