经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » 微信小程序 » 查看文章
微信小程序实现富文本图片宽度自适应的方法
来源:jb51  时间:2019/1/21 9:20:46  对本文有异议

引言:在微信小程序里,比如商品展示页面的商品详情会有图片展示,PC端设置的商品详情是PC端的宽度,所以在小程序里图片会显示不全,这时就应该做相应的处理,使小程序里图片显示正确

思路

  • 把图片的宽度改为手机屏幕对应的宽度

微信小程序需要知道的知识

  • 需要知道微信小程序里有自己的宽度标准,单位为rpx;
  • 针对所有不同尺寸的浏览器,微信小程序里规定屏幕宽为750rpx;

解决

WXML

  1. <view class='html_detail'>
  2. <rich-text nodes='{{artical}}'></rich-text>
  3. </view>

WXS

  1. data={artical:''}
  2.  
  3. async onLoad(){
  4. const json = await api.getDetail();
  5. if(json !== null){
  6. this.artical = util.formatRichText(json.detail.description);
  7. }
  8. }
  9.  

若artical里只有图片,并且图片没有设置style和宽度/高度

util.js

  1. function formatRichText(html){
  2. let newContent= html.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;"');
  3. return newContent;
  4. }
  5.  
  6. module.exports = {
  7. formatRichText
  8. }
  9.  

若artical里包含多种标签

util.js

  1. /**
  2. * 处理富文本里的图片宽度自适应
  3. * 1.去掉img标签里的style、width、height属性
  4. * 2.img标签添加style属性:max-width:100%;height:auto
  5. * 3.修改所有style里的width属性为max-width:100%
  6. * 4.去掉<br/>标签
  7. * @param html
  8. * @returns {void|string|*}
  9. */
  10. function formatRichText(html){
  11. let newContent= html.replace(/<img[^>]*>/gi,function(match,capture){
  12. match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
  13. match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
  14. match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
  15. return match;
  16. });
  17. newContent = newContent.replace(/style="[^"]+"/gi,function(match,capture){
  18. match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
  19. return match;
  20. });
  21. newContent = newContent.replace(/<br[^>]*\/>/gi, '');
  22. newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
  23. return newContent;
  24. }
  25.  
  26. module.exports = {
  27. formatRichText
  28. }
  29.  

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号