在微信小程序开发中,rich-text 标签可以用来显示富文本 html内容,可以渲染部分html标签,全局支持class和style属性,但不支持id属性。
1 基本使用一种最基本的应用场景就是从接口请求加载回来的 html 内容,显示到小程序页面上,常用商品详情等等。 首先,是 wxml 页面元素的使用 <rich-text nodes="{{content}}"></rich-text> 然后在 对应的 js 文件中
Page({
/** * 页面的初始数据 */ data: { content:'<h1>这里是标题</<h1><p>这里是段落内容体系</p>', },
/** * 生命周期函数--监听页面加载 */ onLoad: function (options) {
}, })
2 处理图片自适应问题核心方法就是
<img style="max-width:100%;height:auto;display:block;margin:10px 0;" 将html文本中的img标签中添加自适应的样式
一般应用场景是我们加载详情后,再处理下数据
/** * 例如加载商品详情 */ getdetail: function () { wx.request({ url: '接口地址', data: {'参数key':''}, header: { 'content-type': 'application/json' }, method: 'GET', responseType: 'text', success(res) { console.log(res); if (res.data.code === 0) { //返回的富文本数据 var content = res.data.data.content; that.setData({ //处理图片自适应问题 /** * 此代码段处理目的为,匹配富文本代码中的 <img> 标签,并将其图片的宽度修改为适应屏幕 * max-width:100% --- 图片宽度加以限制,避免超出屏幕 * height:auto --- 高度自适应 * display:block */ contentInfo: content.replace('<img ', '<img style="max-width:100%;height:auto;display:block;margin:10px 0;"') }) } else { console.log('数据加载失败') wx.showToast({ title: res.data.msg, duration: 2000 }) } }, }) }
完毕
|