index.vue 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <template>
  2. <mp-html :content="content|formatRichText" selectable="true" show-img-menu="true" ref="mpHtml" />
  3. </template>
  4. <script>
  5. export default {
  6. name: 'rich-text',
  7. props: {
  8. content: {
  9. type: String,
  10. default: '',
  11. },
  12. },
  13. data() {
  14. return {};
  15. },
  16. created() {
  17. },
  18. filters: {
  19. /**
  20. * 处理富文本里的图片宽度自适应
  21. * 1.去掉img标签里的style、width、height属性
  22. * 2.img标签添加style属性:max-width:100%;height:auto
  23. * 3.修改所有style里的width属性为max-width:100%
  24. * 4.去掉<br/>标签
  25. * @param html
  26. * @returns {void|string|*}
  27. *
  28. */
  29. formatRichText(html) { //控制小程序中图片大小
  30. let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
  31. match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
  32. match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
  33. match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
  34. return match;
  35. });
  36. newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
  37. match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi,
  38. 'max-width:100%;');
  39. return match;
  40. });
  41. newContent = newContent.replace(/<br[^>]*\/>/gi, '');
  42. newContent = newContent.replace(/<img src="\/dev-api|<img src="\/prod-api/gi,
  43. `<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;" src="${process.env.UNI_FILE_PREFIX}`);
  44. newContent = newContent.replace(/<iframe(([\s\S])*?)<\/iframe>/ig, function (match, capture) {
  45. match = match.replace('iframe', 'video');
  46. match = match.replace(/<video/gi,
  47. '<video style="width:100%;height:auto;display:inline-block;margin:10rpx auto;"')
  48. .replace(/style='[^']+'/gi, 'style=\'max-width:100%;height:auto;display:inline-block;margin:10rpx auto;\'');
  49. match = match.replace(/src="/gi, `src="${process.env.UNI_FILE_PREFIX}`)
  50. .replace(/src='/gi, `src='${process.env.UNI_FILE_PREFIX}`);
  51. return match;
  52. });
  53. return newContent;
  54. },
  55. },
  56. methods: {
  57. },
  58. };
  59. </script>
  60. <style lang="scss" src="./index.scss" />;