微信小程序_实现markdown支持代码复制功能
⭐ 前言
⭐ 复制代码功能实现
基于towxml渲染markdown 定位
因为是基于towxml渲染的markdown 通过渲染元素快速定位代码块 code 的位置 通过选择元素,可找到class 名称h2w__viewParent即为渲染代码块的元素布局。
h2w__code language-css 类名下是渲染的代码块
定位元素的代码块渲染class
查找样式的判断源码
通过new mardown的过程我们找到class是通过attr的class注入
attr注入属性用来判断是否是代码块 code
区分的标志:tag是否为code使用includes判断 e.tag.includes(‘code’)
// 代码块判断 if(e.tag.includes(code)||item.name.includes(code)||attrs.class.includes(code)){ attrs.isCodeBlock=true attrs.element=e }
复制代码样式及事件绑定
样式
<view wx:if="{ {item.attrs.isCodeBlock}}" bindtap="cloneCode" data-code="{ {item}}" data-attr-data="{ {item.attrs.data}}" style="float: right;position: relative;top:-20px;user-select: none;"> 复制代码 </view>
事件绑定
cloneCode(e) { const { code } = e.target.dataset const { attrs } = code const { element } = attrs const { child } = element let lineCount = 0 const getCodeFormat = (array) => { let text = array.forEach(item => { if (item.tag && item.tag.includes(ul)) { // 多少行判断 lineCount = item.child.length } else if (item.tag && item.tag.includes(span)) { // 子集的text 递归回去 text += getCodeFormat(item.child) } else if (item.tag && item.tag.includes(br)) { // 换行标志 text += } else if (item.text) { // 文字 text += item.text } }) return text } let content = getCodeFormat(child) wx.setClipboardData({ data: content }) wx.getClipboardData({ success: (option) => { console.log(option) }, }) }
效果
复制打印测试和代码块一样,完全ok! 复制成功!
⭐ 结束
欢迎阅读,祝你生活愉快!
上一篇:
uniapp开发微信小程序-2.页面制作
下一篇:
微信公众号推送天气预报