把页面某内容放入粘贴板中

在很多的网站,相信大家都有看到,点击一个按钮之后,就把对应的代码或者地址放置到了粘贴板中,这种操作粘贴板的方法是什么呢,下面就来跟大家分享一下;

 1 function copyToClipboard(elem) {
 2 // create hidden text element, if it doesn't already exist
 3 var targetId = "_hiddenCopyText_";
 4 var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
 5 var origSelectionStart, origSelectionEnd;
 6 if (isInput) {
 7 // can just use the original source element for the selection and copy
 8 target = elem;
 9 origSelectionStart = elem.selectionStart;
10 origSelectionEnd = elem.selectionEnd;
11 } else {
12 // must use a temporary form element for the selection and copy
13 target = document.getElementById(targetId);
14 if (!target) {
15 var target = document.createElement("textarea");
16 target.style.position = "absolute";
17 target.style.left = "-9999px";
18 target.style.top = "0";
19 target.id = targetId;
20 document.body.appendChild(target);
21 }
22 target.textContent = elem.textContent;
23 }
24 // select the content
25 var currentFocus = document.activeElement;
26 target.focus();
27 target.setSelectionRange(0, target.value.length);
28 // copy the selection
29 var succeed;
30 try {
31 succeed = document.execCommand("copy");
32 } catch(e) {
33 succeed = false;
34 }
35 // restore original focus
36 if (currentFocus && typeof currentFocus.focus === "function") {
37 currentFocus.focus();
38 }
39 if (isInput) {
40 // restore prior selection
41 elem.setSelectionRange(origSelectionStart, origSelectionEnd);
42 } else {
43 // clear temporary content
44 target.textContent = "";
45 }
46 return succeed;
47 }
48 
49 //调用
50 copyToClipboard(document.getElementById("name"));//这里传入的参数是要把哪一个标签里面的内容使用,就放入哪个元素即可;

操作系统的东西,当然要原生的js兼容性更好了赛;看起来还是很方便吧!

posted @ 2017-02-07 09:40  赤恩吉烨  阅读(256)  评论(1编辑  收藏  举报