js复制文本

微信小程序:

1、如果需要长按复制文本,首先必须使用<text>标签,并且将selectable属性设置为true

<text selectable='true'>xxxx</text>

2、按钮复制,使用微信内置api:wx.setClipboardData API

    wx.setClipboardData({
      data: '需要复制的数据',
      success: function (res) {
     //复制成功的操作
      }
    });

 原生js实现文本复制:

let textarea = document.createElement("textarea")
textarea.value = txt
textarea.readOnly = "readOnly"
document.body.appendChild(textarea)
textarea.select() // 选中文本内容
// textarea.setSelectionRange(0, txt.length) 
let result = document.execCommand("copy")
if (result) {
    this.showToast({
        title: '复制成功'
    })
}
textarea.remove()

uni-app

// #ifdef H5 
let textarea = document.createElement("textarea")
textarea.value = txt
textarea.readOnly = "readOnly"
document.body.appendChild(textarea)
textarea.select() // 选中文本内容
// textarea.setSelectionRange(0, txt.length) 
let result = document.execCommand("copy")
if (result) {
    uni.showToast({
        title: '复制成功'
    })
}
textarea.remove()
// #endif

// #ifndef H5
    uni.setClipboardData({
        data: txt,
        success: (res) => {
            console.log(res, 'copy')
            uni.showToast({
                title: '复制成功'
            })
        },
        fail: (error) => {
            console.log(error, 'copyerror')
        }
    })
// #endif

 

posted @ 2019-07-11 13:43  霜~  阅读(4114)  评论(0编辑  收藏  举报