"
"
需求描述
在UniApp中通过点击一个按钮实现复制某段文本的内容。
实现方法
使用uni.setClipboardData实现
利用 uniapp 提供的 api setClipboardData
,但是这个 api 兼容 APP 端,不兼容 H5 端,那么我们还需要对 H5 端进行处理;
点击复制按钮,实现复制downUrl.url,代码如下:
view:
<view class="down">
<p style="color:cornflowerblue;">{{downUrl.url}}</p>
</view>
<view><button @click="copy">点击按钮复制</button></view>
js:
copy() {
let result
// #ifndef H5
//uni.setClipboardData方法就是讲内容复制到粘贴板
uni.setClipboardData({
data: this.downUrl.url, //要被复制的内容
success: () => { //复制成功的回调函数
uni.showToast({ //提示
title: '复制成功'
})
}
});
// #endif
// #ifdef H5
let textarea = document.createElement("textarea")
textarea.value = this.downUrl.url
textarea.readOnly = "readOnly"
document.body.appendChild(textarea)
textarea.select() // 选中文本内容
textarea.setSelectionRange(0, info.length)
uni.showToast({ //提示
title: '复制成功'
})
result = document.execCommand("copy")
textarea.remove()
// #endif
}