Note that this is not to copy the text of the selected content, but to copy the text content in the text box.
Example 1: Copy the content of the input input box
var content = 'this is a content!'
function copyText(content) {
if (!content) {
alert('复制内容为空')
return
}
let cInput = document.createElement("input")
document.body.appendChild(cInput)
cInput.select() // 选取文本框内容
// 执行浏览器复制命令
// 复制命令会将当前选中的内容复制到剪切板中(这里就是创建的input标签)
// Input要在正常的编辑状态下原生复制方法才会生效
document.execCommand("copy")
// 复制成功后再将构造的标签 移除
document.body.removeChild(cInput)
alert('复制成功!')
}
===> 输出
this is a content!
Note: Why use the textarea tag here? Because the textarea tag supports newlines, tabulation, etc.
Example 2: Copy textarea content and output in newline
var content = '1,2,3,4,5,6,7,8,9'
function copyText(content) {
if (!content) {
alert('复制内容为空')
return
}
let cInput = document.createElement("textarea")
cInput.value = content?.replaceAll(',', '\n')
document.body.appendChild(cInput)
cInput.select() // 选取文本框内容
// 执行浏览器复制命令
// 复制命令会将当前选中的内容复制到剪切板中(这里就是创建的input标签)
// Input要在正常的编辑状态下原生复制方法才会生效
document.execCommand("copy")
// 复制成功后再将构造的标签 移除
document.body.removeChild(cInput)
alert('复制成功!')
}
====> 输出
1
2
3
4
...
Example 3: Copy textarea content, output in table and newline form
var content = '1,2,3;4,5,6;7,8,9'
function copyText(content) {
if (!content) {
alert('复制内容为空')
return
}
let cInput = document.createElement("textarea")
// 按分号换行,按逗号Tab(具体分割方式还需要看文本内容)
cInput.value = content?.replaceAll(',', '\t').replaceAll(';', '\n')
document.body.appendChild(cInput)
cInput.select() // 选取文本框内容
// 执行浏览器复制命令
// 复制命令会将当前选中的内容复制到剪切板中(这里就是创建的input标签)
// Input要在正常的编辑状态下原生复制方法才会生效
document.execCommand("copy")
// 复制成功后再将构造的标签 移除
document.body.removeChild(cInput)
alert('复制成功!')
}
===> 输出
1 2 3
4 5 6
7 8 9