最近做了一个前端项目,其中有需求:通过button直接把input或者textarea里的值复制到粘贴板里。下面小编把我实现思路及代码分享给大家,大家可以直接引入项目中。
具体代码如下所示:
function copyToClipboard(elem) { // create hidden text element, if it doesn't already exist var targetId = "_hiddenCopyText_"; var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA"; var origSelectionStart, origSelectionEnd; if (isInput) { // can just use the original source element for the selection and copy target = elem; origSelectionStart = elem.selectionStart; origSelectionEnd = elem.selectionEnd; } else { // must use a temporary form element for the selection and copy target = document.getElementById(targetId); if (!target) { var target = document.createElement("textarea"); target.style.position = "absolute"; target.style.left = "-9999px"; target.style.top = "0"; target.id = targetId; document.body.appendChild(target); } target.textContent = elem.textContent; } // select the content var currentFocus = document.activeElement; target.focus(); target.setSelectionRange(0, target.value.length); // copy the selection var succeed; try { succeed = document.execCommand("copy"); } catch(e) { succeed = false; } // restore original focus if (currentFocus && typeof currentFocus.focus === "function") { currentFocus.focus(); } if (isInput) { // restore prior selection elem.setSelectionRange(origSelectionStart, origSelectionEnd); } else { // clear temporary content target.textContent = ""; } return succeed; }
我们可以这样直接调用这个方法:
copyToClipboard(document.getElementById("name"));
这样id为name的值进入了粘贴板了。
关于JavaScript实现复制内容到粘贴板代码小编就给大家介绍到这里,希望对大家有所帮助!
标签:
js复制粘贴,js复制到粘贴板
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
暂无“JavaScript实现复制内容到粘贴板代码”评论...
更新动态
20240527
20240527
- 赵传《赵传歌曲合集》[320K/MP3][692.4MB]
- [发烧极品]群星《天籁试音极品-震撼(西乐篇)》2CD[WAV+CUE]
- 群星-《发烧中的国语时代曲K2HD》[WAV+CUE]
- [珍纳精选]人声发烧天碟珍藏版《JHEENALODWICKGREATEST》1:1直刻[WAV+CUE]
- 群星-《发烧中的精选SAMPLERAUDIOPHILE》AMCD限量版[WAV+CUE]
- 群星《情缘难续·发烧人声》(黑胶)2CD[WAV+CUE]
- 吴淑敏.2003-为情为爱梦一生【巨人唱片】【WAV+CUE】
- 张国荣《张国荣歌曲合集》[320K/MP3][334.4MB]
- 周华健《周华健歌曲合集》[320K/MP3][521MB]
- 张韶涵《张韶涵歌曲合集》[320K/MP3][486.2MB]
- 陈芯怡.2023-漫行日志【鼎乐】【FLAC分轨】
- 梁韵.1986-香港夜上海(TP版)【上海音像】【WAV+CUE】
- 韦唯-我相信中国[上海文艺音像首版]WAV+CUE
- 张雨生《张雨生歌曲合集》[320K/MP3][196MB]
- 张杰《张杰歌曲合集》[320K/MP3][300.4MB]