1.原生的浏览器复制方式,一般都是在浏览器上使用
单独定义一个h5-copy.js文件。用于复用 复制粘贴功能
h5-copy.js
export default function h5Copy(content) {
console.log(content);
if (!document.queryCommandSupported('copy')) {
// 不支持
uni.showToast({
title:'您当前的应用环境不支持自动复制内容......',
icon:'none'
})
return false
}
let textarea = document.createElement("textarea")
textarea.value = content
textarea.readOnly = "readOnly"
document.body.appendChild(textarea)
textarea.select() // 选择对象
textarea.setSelectionRange(0, content.length) //复制的内容的范围
let result = document.execCommand("copy") // 执行浏览器复制命令
textarea.remove()
return result
}
然后在文件中使用
<template>
<view>
<button type="primary" size="mini" @click="copy">文字复制</button>
</view>
</template>
<script>
import h5Copy from '@/utils/h5-copy.js'
export default {
data() {
return {
};
},
methods:{
copy(){
// #ifdef H5
let res = h5Copy('传入要复制的内容')
if (res) {
uni.showToast({
title:'复制成功',
icon:"success"
})
//window.location.href = "weixin://";
} else {
uni.showToast({
title:'复制失败',
icon:"none"
})
}
// #endif
// #ifdef APP-PLUS
uni.setClipboardData({
data: '要复制的内容',
success: () => {
//复制成功之后的回调 do something here
uni.showToast({
title: '复制成功'
})
},
fail: () => {
//复制失败之后的回调 do something here
uni.showToast({
title: '复制失败',
icon: "none"
})
}
});
// #endif
}
}
}
</script>
<style lang="scss"></style>
如果要是在uniapp中使用app与h5 同时都实现复制粘贴功能的话:
- H5可使用上述方式实现,
- app可以用uniapp官网的复制粘贴的api接口