⼩程序实现富⽂本图⽚宽度⾃适应的⽅法
引⾔:在⼩程序⾥,⽐如商品展⽰页⾯的商品详情会有图⽚展⽰,PC端设置的商品详情是PC端的宽度,所以在⼩程序⾥图⽚会显⽰不全,这时就应该做相应的处理,使⼩程序⾥图⽚显⽰正确
思路
把图⽚的宽度改为⼿机屏幕对应的宽度
⼩程序需要知道的知识
需要知道⼩程序⾥有⾃⼰的宽度标准,单位为rpx;
针对所有不同尺⼨的浏览器,⼩程序⾥规定屏幕宽为750rpx;
解决
WXML
<view class='html_detail'>
<rich-text nodes='{{artical}}'></rich-text>
</view>
WXS
data={artical:''}
async onLoad(){
html富文本框const json = Detail();
if(json !== null){
this.artical = util.formatRichText(json.detail.description);
}
}
若artical⾥只有图⽚,并且图⽚没有设置style和宽度/⾼度
util.js
function formatRichText(html){
let newContent= place(/\<img/gi, '<img ');
return newContent;
}
formatRichText
}
若artical⾥包含多种标签
util.js
/**
* 处理富⽂本⾥的图⽚宽度⾃适应
* 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= place(/<img[^>]*>/gi,function(match,capture){
match = place(/]+"/gi, '').replace(/style='[^']+'/gi, '');
match = place(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
match = place(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
return match;
});
newContent = place(/]+"/gi,function(match,capture){
match = place(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
return match;
});
newContent = place(/<br[^>]*\/>/gi, '');
newContent = place(/\<img/gi, '<img '); return newContent;
}
formatRichText
}
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论