1. Implementation without introducing external components
<!-- index.wxml -->
<view>
<!-- 长按复制 -->
<view bindlongtap="copyText" data-key="{
{item.cdkey}}">{
{ item.cdkey }}</view>
<text bindlongtap="copyText" data-key="{
{item.cdkey}}">{
{ item.cdkey }}</text>
<!-- 一键复制 -->
<view bindtap="copyText" data-key="{
{item.cdkey}}" > 复制 </view>
</view>
bindlongtap
The method can be used for long-press copy , and the event is triggered after the finger is long-pressed for 500ms.- One-click copy can use
bindtap
the method , click to trigger the event immediately.
// index.js
copyText(e) {
let key = e.currentTarget.dataset.key;
wx.setClipboardData({
//设置系统剪贴板的内容
data: key,
success(res) {
console.log(res, key);
wx.getClipboardData({
// 获取系统剪贴板的内容
success(res) {
wx.showToast({
title: '复制成功',
})
}
})
}
})
}
Note: Styles can add suitable styles by themselves
Effect:
Second, the implementation of the introduction of external components
select-text
optional text component. This component has two usage modes: long press to display the selection area, which is consistent with the default effect of the browser; long press to display the copy button, click to copy and copy all content to the clipboard, which is commonly used in chat dialog boxes and other scenarios .
It should be noted that in order to hide the copy button when clicking other areas, the developer can listen to the tap event on the outermost layer of the page and assign the evt object to on-document-tap.
Install
npm install @miniprogram-component-plus/select-text
In page page.json
// page.json
{
"usingComponents": {
"mp-select-text": "@miniprogram-component-plus/select-text"
}
}
In the page index.wxml
<view bind:tap="handleTap">
<view class="demo-block">
<block wx:for="{
{arr}}" wx:key="placement">
<view class="list-item">
<mp-select-text
show-copy-btn
placement="{
{item.placement}}"
value="{
{item.value}}"
data-id="{
{index}}"
bindcopy="onCopy"
on-document-tap="{
{evt}}"
>
</mp-select-text>
</view>
</block>
<view class="list-item">
<mp-select-text value="默认的长按效果与浏览器一致"></mp-select-text>
</view>
</view>
</view>
Effect
For specific implementation, please refer to: select-text component
Hurry up and try it~