当前位置: 首页 > news >正文

uniapp 富文本rich-text 文本首行缩进和图片居中

1. uniapp 富文本rich-text 文本首行缩进和图片居中

1.1. rich-text 文本首行缩进

  使用 rich-text 组件渲染html格式的代码,常常因为不能自定义css导致文本不能缩进,以及图片不能居中等问题,这里可以考虑使用js的replace方法,替换字符串,然后在渲染的同时加载行内样式。

//页面上加载
<rich-text :nodes="goodsDetail.detail"></rich-text>
var richtext=  this.goodsDetail.detail;
const regex = new RegExp('<img', 'gi');
richtext = richtext.replace(regex, `<img style="max-width:100%;height:auto;display:block;"`);
this.goodsDetail.detail = richtext;

  replace里的g表示全局替换,而每个关键词前面的\则为转义字符,在针对html类的标签替换的时候,是必不可少的。这个方法还支持拓展关键词增加如果有需求可以自行添加,需要自定义的css样式则可以在所替换的字符串关键词里定义。

1.2. 富文本图片居中

1.2.1. 问题

  uni-app - 完美解决 rich-text 富文本解析图片无法自适应宽高问题,图片超出屏幕宽度且不受控。

1.2.2. 解决方案

  对显示前的富文本数据,使用正则进行替换处理图片标签,加入自适应属性样式。

<rich-text :nodes="repairRichText('<b>您的富文本内容</b>')" />
/*** 修复富文本图片宽度* @description 解决图片宽高超出显示不全问题(让其自适应)* @param {String} html - 富文本* @return String*/
repairRichText(html) {// 去掉<img>中style /width / height属性let newContent = html.replace(/<img[^>]*>/gi, (match) => {match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '')match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '')match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '')// 去除 style=""这样的属性(非必须,不需要可自行注释)match = match.replace(/style\s*=\s*(["'])(?:(?!\1).)*\1/gi, '')return match})// 修改所有style里的width属性为max-width:100%newContent = newContent.replace(/style="[^"]+"/gi, (match) => {match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;')return match})// 去掉所有<br/>标签newContent = newContent.replace(/<br[^>]*\/>/gi, '')// img标签添加style属性:max-width:100%;height:autonewContent = newContent.replace(/\<img/gi,'<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"')// returnreturn newContent;
}
http://www.dtcms.com/a/311116.html

相关文章:

  • Day 29: 复习
  • 音视频学习(四十五):声音的产生
  • 数据集-目标检测系列- 地球仪 数据集 globe>> DataBall
  • 前端应用权限设计面面观
  • 网络基础实操篇-05-路由基础-最佳实践
  • 【机器学习】非线性分类算法(上):KNN(基于距离相似度)与朴素(特征独立)贝叶斯(基于概率统计)
  • MybatisPlus-逻辑删除
  • 【ElementPlus】深入探索ElementPlus:前端界面的全能组件库
  • 【Conda】配置Conda镜像源
  • 【Linux】vim—基操
  • 网易云音乐硬刚腾讯系!起诉SM娱乐滥用市场支配地位
  • 【深度学习②】| DNN篇
  • SmartCLIP:具有识别保证的模块化视觉-语言对齐
  • 基于OAuth2与JWT的微服务API安全实战经验分享
  • Java 垃圾回收机制:自动化内存管理的艺术与科学
  • Python 程序设计讲义(54):Python 的函数——函数概述
  • Linux iptables防火墙操作
  • 一种基于入侵杂草优化算法(IWO)的聚类算法,并与K-Means、高斯混合模型(GMM)进行对比,Matlab
  • 网安-中间件(updating..)
  • HarmonyOS NEXT系列之定制化构建制品
  • HarmonyOS 开发:基于 ArkUI 实现复杂表单验证的最佳实践
  • 电子电气架构 --- 汽车网络安全概述
  • lumerical——布拉格光栅(2)
  • Baumer工业相机堡盟工业相机如何通过YoloV8深度学习模型实现道路车辆事故的检测识别(C#代码UI界面版)
  • LLM隐藏层状态: outputs.hidden_states 是 MLP Residual 还是 Layer Norm
  • 【前端:Html】--1.1.基础语法
  • 在 Elasticsearch 中落地 Learning to Rank(LTR)
  • 修改git commit 提交版本的描述信息
  • 【算法笔记 day four】二分查找
  • realIADD3复现笔记