

JS 实现 点击按钮复制文本到剪贴板中
source link: https://www.haorooms.com/post/js_copy_text
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

js复制文本到剪切板有很多方法,很多朋友会用开源库,其实纯js的方式实现也很简单。关于复制和剪切板,之前也写过很多文章,例如。 javascript execCommand,复文本框神器 记录一下js光标位置及复制和剪切板 文件上传之剪切板上传及大文件分片上传和断点续传
今天分享一下简单的copy方案。
navigator.clipboard.writeText 方案
这个方案不支持ie,比较简单
var text = 'Example text to appear on clipboard by haorooms.com';
navigator.clipboard.writeText(text).then(
function () {
console.log('Haorooms tips: Copying to clipboard was successful!');
},
function (err) {
console.error('haorooms tips: Could not copy text: ', err);
}
);
document.execCommand(‘copy’)
这些方案博客之前有介绍。可以综合两种方案:
function fallbackCopyTextToClipboard(text) {
var textArea = document.createElement('textarea');
textArea.value = text;
// Avoid scrolling to bottom
textArea.style.top = '0';
textArea.style.left = '0';
textArea.style.position = 'fixed';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Fallback: Copying text command was ' + msg);
} catch (err) {
console.error('Fallback: Oops, unable to copy', err);
}
document.body.removeChild(textArea);
}
function copyTextToClipboard(text) {
if (!navigator.clipboard) {
fallbackCopyTextToClipboard(text);
return;
}
navigator.clipboard.writeText(text).then(
function () {
console.log('Async: Copying to clipboard was successful!');
},
function (err) {
console.error('Async: Could not copy text: ', err);
}
);
}
var copyBobBtn = document.querySelector('.js-copy-haorooms-btn')
copyBobBtn.addEventListener('click', function (event) {
copyTextToClipboard(haoroomsinputtext.value);
});
<input type="text" id="haoroomsinputtext" />
<button class="js-copy-haorooms-btn">haoroomscopybtn</button>
此demo可以之间copy到html种之间运行。
Recommend
-
97
JavaScript复制内容到剪贴板
-
32
-
28
每日前端夜话 第332篇 翻译: 疯狂的技术宅 作者:Sanwar ranwa 来源:dzone 正文共:1376 字 预...
-
13
需求如下:将index.txt 的内容进行格式转换后复制到剪贴板。index.txt莲子心中苦,梨儿腹内酸。--明末清初.金圣叹 雨入花心,自成甘苦。水归器内,各现方圆。--明末清初.金圣叹 真读书人天下少,不...
-
7
js点击一键复制文本功能(clipboard)时间: 08/22/2020作者: ll浏览量: 1495有时候我们遇到需求是,点击按钮复制文本,方便用户直接复制粘贴所需要的内容,这个功能很多网站或者应用都是有的功能。怎么...
-
8
在 Web 中,大部分按钮可能都是平平无奇的,有时候为了强调品牌特殊或者满足特殊功能,可能需要给按钮添加一点点击动效。比如,用过
-
8
CSS实现防止按钮重复点击,双击进入两次单机的情况 2022年11月17日 23次浏览 之前有文章写过如何避免双击进入两次单机的情况,当然...
-
3
在...
-
6
如何在HTML中利用复制函数实现点击即复制的功能 | VPS小白 VPS小白 >
-
4
JavaScript 点击按钮一键复制指定文本内容 2023-07-27 4 0 navigator.clipboard.writeText('message') 该方法更为简单实用,且兼容性好,废话不多说,直接上代码:
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK