uni-app小程序图片v-html自适应问题

前言

用v-html渲染富文本框,发现小程序图片没有办法自适应
采用css去修改,发现不生效

img{
	width: 750upx!important;
}

解决办法

uni的v-html转换成小程序是rich-text标签,则我们直接使用rich-text来实现富文本的渲染

<rich-text :nodes="details.newsConten | filtersRichText"></rich-text>

我们使用过滤器来把img的标签拿出来,在放css样式

filters: {
	filtersRichText(html) { //控制小程序中图片大小
		let newContent = html.replace(/<img[^>]*>/gi, (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, (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:inline-block;margin:10rpx auto;"');
		return newContent;
	}
},

效果展示

在这里插入图片描述

补充

如果图片想展示自定义样式,那么我们可以不添加style,而改用class,在我们的css中加上class样式也可以

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
uni-app中,可以通过自定义指令来实现自适应DPR加载图片,并且可以兼容小程序、H5和App。具体步骤如下: 1. 在项目的`main.js`中注册自定义指令: ```javascript import Vue from 'vue'; import App from './App'; Vue.config.productionTip = false; // 注册自定义指令 Vue.directive('adapt-img', { bind: function (el, binding) { let dpr = uni.getSystemInfoSync().pixelRatio; let value = binding.value; if (value) { if (dpr >= 3 && value.indexOf('@3x') !== -1) { el.setAttribute('src', value.replace('@3x', '')); } else if (dpr >= 2 && value.indexOf('@2x') !== -1) { el.setAttribute('src', value.replace('@2x', '')); } else { el.setAttribute('src', value); } } }, }); App.mpType = 'app'; const app = new Vue({ ...App, }); app.$mount(); ``` 这里注册了一个名为`adapt-img`的自定义指令,当该指令绑定到元素上时,会根据当前设备的DPR加载对应的图片。这里使用了uni-app提供的`uni.getSystemInfoSync().pixelRatio`来获取当前设备的DPR,从而实现了兼容小程序、H5和App的效果。 2. 在需要使用自适应DPR加载图片的地方,将自定义指令`adapt-img`绑定到`<img>`标签上,并设置图片路径: ```html <template> <div class="demo"> <img v-adapt-img src="@/static/img/[email protected]" /> </div> </template> <style> .demo img { width: 100px; height: 100px; } </style> ``` 这里将自定义指令`adapt-img`绑定到`<img>`标签上,并设置图片路径为`@/static/img/[email protected]`。在绑定指令时,可以将图片路径作为指令的值传递过去。 3. 在图片文件夹中,只需要提供@2x和@3x倍图即可,不需要提供@1x倍图。 这样,当页面加载时,自定义指令会根据当前设备的DPR加载对应的图片,如果当前设备的DPR为1,则会加载原始图片。 需要注意的是,如果图片文件名中包含了`@2x`或`@3x`,需要在指令中进行判断并替换。如果图片文件名中没有包含`@2x`或`@3x`,则直接加载原始图片。同时,由于uni-app的兼容性特性,该自定义指令可以兼容小程序、H5和App

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

荒男

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值