- 我的需求是给一段富文本的手机号和地址加样式并可拨打电话,导航地址;
- mp-html用的富文本插件是这个;
- 自己用正则把需要特殊标记的内容提取出来,如需要提取手机号,地址等,如下用标签<a href="#" data-type="phone" data-content="电话" style="color: #0088cc; text-decoration: underline;">电话</a>显示;
javascript
//处理地址
let processedStr = str.replace(/位于([^。;,,]+?)(?=[。;,,]|$)/g,
(match, address) => {
return `位于<a href="#" data-type="address" data-address="${address}" style="color: #0088cc; text-decoration: underline;">${address}</a>`;
}
);
// 处理电话号码
processedStr = processedStr.replace(phoneReg, (match) => {
// 保持原始显示格式,但去除横线用于拨号 这里用a标签代替拨打手机号
const purePhone = match.replace(/-/g, '');
return `<a href="#" data-type="phone" data-phone="${purePhone}" style="color: #0088cc; text-decoration: underline;">${match}</a>`;
});
return processedStr;
html
<mp-html content="{{item.answer}}"
bindlinktap="linktap"
selectable="true"
bindimgtap="imgtap" />
<!-- bindlinktap可监听到a标签的点击事件 -->
<!-- bindimgtap可监听到图片预览事件 -->
- 给mp-html添加bindlinktap="linktap",bindlinktap事件可以监听到a标签的点击,通过type属性来判断内容类型,就可以监听到类型去处理对应的逻辑;