微信小程序_实现markdown支持代码复制功能

本文介绍了如何在微信小程序中实现Markdown的代码复制功能,通过towxml渲染定位代码块,结合事件绑定和样式设置,成功实现了代码的复制到粘贴板。
摘要由CSDN通过智能技术生成

⭐ 前言

大家好,我是yma16,不止前端,本文将介绍微信小程序中 markdown的代码复制功能实现。
往期微信小程序文章
小程序自定义微信昵称和头像
小程序制作markdown博客
小程序结合chatgpt制作聊天页面
小程序组件传值
小程序复制到粘贴板的功能实现

⭐ 复制代码功能实现

基于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 += '\n'
					}
					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!
在这里插入图片描述
复制成功!
在这里插入图片描述

⭐ 结束

欢迎阅读,祝你生活愉快!
在这里插入图片描述

  • 12
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yma16

感谢支持!共勉!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值