話不多說直接上代碼:
function copyToClipboard(elem) {
? ? ? ? ? ? var targetId = "_hiddenCopyText_";
? ? ? ? ? ? var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
? ? ? ? ? ? var origSelectionStart, origSelectionEnd;
? ? ? ? ? ? if (isInput) {
? ? ? ? ? ? ? ? // 如果是input標簽或textarea览濒,則直接指定該節(jié)點
? ? ? ? ? ? ? ? target = elem;
? ? ? ? ? ? ? ? origSelectionStart = elem.selectionStart;
? ? ? ? ? ? ? ? origSelectionEnd = elem.selectionEnd;
? ? ? ? ? ? ? ? console.dir( elem)
? ? ? ? ? ? ? ? console.log(? elem.selectionEnd)
? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? // 如果不是兽叮,則使用節(jié)點的textContent
? ? ? ? ? ? ? ? target = document.getElementById(targetId);
? ? ? ? ? ? ? ? if (!target) {
? ? ? ? ? ? ? ? ? ? //如果不存在,則創(chuàng)建一個
? ? ? ? ? ? ? ? ? ? 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;
? ? ? ? ? ? }
? ? ? ? ? ? // 聚焦目標節(jié)點恶导,選中它的內容
? ? ? ? ? ? var currentFocus = document.activeElement;
? ? ? ? ? ? target.focus();
? ? ? ? ? ? target.setSelectionRange(0, target.value.length);
? ? ? ? ? ? // 進行復制操作
? ? ? ? ? ? var succeed;
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? succeed = document.execCommand("copy");
? ? ? ? ? ? } catch(e) {
? ? ? ? ? ? ? ? succeed = false;
? ? ? ? ? ? }
? ? ? ? ? ? // 不再聚焦
? ? ? ? ? ? if (currentFocus && typeof currentFocus.focus === "function") {
? ? ? ? ? ? ? ? currentFocus.focus();
? ? ? ? ? ? }
? ? ? ? ? ? if (isInput) {
? ? ? ? ? ? ? ? // 清空臨時數據
? ? ? ? ? ? ? ? elem.setSelectionRange(0, 0);
? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? // 清空臨時數據
? ? ? ? ? ? ? ? target.textContent = "";
? ? ? ? ? ? }
? ? ? ? ? ? return succeed;
? ? ? ? }
? ? ? ? $("#copy").on('click',function(){
? ? ? ? var copytxt=document.querySelector('#copyTxt');
? ? ? ? ? ? copyToClipboard(copytxt);
? ? ? ? });
tag:前端實現復制功能主要的API有:
input : selectionStart , slectionEnd ,setSelectionRange?
document : ?execCommand;
思路如下:
將我們想要復制的內容用 input.setSelectionRange( num, num ) 進行選擇: 之后再用document.exeCommand('copy') ;方法進行復制 !