900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > JavaScript实现复制内容到粘贴板代码【javascript】

JavaScript实现复制内容到粘贴板代码【javascript】

时间:2024-05-17 19:34:56

相关推荐

JavaScript实现复制内容到粘贴板代码【javascript】

web前端|js教程

js复制粘贴,js复制到粘贴板

web前端-js教程

最近做了一个前端项目,其中有需求:通过button直接把input或者textarea里的值复制到粘贴板里。下面小编把我实现思路及代码分享给大家,大家可以直接引入项目中。

砖石买吗源码公司,vscode第一行,Ubuntu列举服务,tomcat 不能访问自己,python甲鱼爬虫,getarray php,乌市seo 网络推广口碑推荐,iis 怎么绑定网站二级目录,discuz响应模板下载lzw

具体代码如下所示:

技术网址之家带后台版源码,vscode改LF合适,ubuntu指令cd,tomcat端口查询,sqlite是否支持多线程,音量条调节jquery插件,前端三大框架哪个好找工作,农村雨天爬虫子视频,php多维数组 json,seo软件代理分类,国外化妆品网站模板,网页图片固定位置,网页表格模板lzw

function copyToClipboard(elem) {// create hidden text element, if it doesn already existvar 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 copytarget = elem;origSelectionStart = elem.selectionStart;origSelectionEnd = elem.selectionEnd;} else {// must use a temporary form element for the selection and copytarget = 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 contentvar currentFocus = document.activeElement;target.focus();target.setSelectionRange(0, target.value.length);// copy the selectionvar succeed;try {succeed = document.execCommand("copy");} catch(e) {succeed = false;}// restore original focusif (currentFocus && typeof currentFocus.focus === "function") {currentFocus.focus();}if (isInput) {// restore prior selectionelem.setSelectionRange(origSelectionStart, origSelectionEnd);} else {// clear temporary contenttarget.textContent = "";}return succeed;}

我们可以这样直接调用这个方法:

博客主页html源码,ubuntu字符有乱码,shell爬虫网页信,引入,北京seo资源lzw

copyToClipboard(document.getElementById("name"));

这样id为name的值进入了粘贴板了。

关于JavaScript实现复制内容到粘贴板代码小编就给大家介绍到这里,希望对大家有所帮助!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。