概要:
- 下周將會上線一個功能,表述為點擊按鈕復制某個dom下的內容或文本.百度后得到一個簡單粗暴的解決方式:
window.clipboardData.setData ("Text", "demo"); - 但是,本人編寫demo運行后發(fā)現(xiàn)報錯:
jsonp.html:15 Uncaught TypeError: Cannot read property 'setData' of undefined - 查詢相關資料,發(fā)現(xiàn)MSDN (https://msdn.microsoft.com/en-us/library/ms535220(v=vs.85).aspx) 中有這么一行附注:
This object is available in script as of Microsoft Internet Explorer 5. -
http://help.dottoro.com/ljctuhrg.php 也表示該方法出于對安全性的考慮,現(xiàn)在只支持IE;
In Firefox, Opera, Google Chrome and Safari, use the execCommand method with the 'Paste' command to retrieve and with the 'Copy' command to set the text content of the clipboard. Because of security restrictions, this method may not always work, see Example 2 for details.
解決思路:
參考資料: http://help.dottoro.com/ljctuhrg.php
- 1.對于IE直接調用clipboardData()方法,省心省事;
- 2.創(chuàng)建一個"隱形"的臨時dom用來存儲目標參數(shù);
- 3.對于非IE,創(chuàng)建一個range對象;
- 4.模擬一次選中操作;
- 5.嘗試通過上面創(chuàng)建的dom作為"中間變量"模擬一次In操作;
- 6.嘗試在FireFox下經(jīng)行授權操作;
- 7.嘗試通過dom再進行一次Out操作;
- 8.刪除臨時dom;
代碼:
function CopyToClipboard (input) {
var textToClipboard = input;
var success = true;
if (window.clipboardData) { // Internet Explorer
window.clipboardData.setData ("Text", textToClipboard);
}
else {
// create a temporary element for the execCommand method
var forExecElement = CreateElementForExecCommand (textToClipboard);
/* Select the contents of the element
(the execCommand for 'copy' method works on the selection) */
SelectContent (forExecElement);
var supported = true;
// UniversalXPConnect privilege is required for clipboard access in Firefox
try {
if (window.netscape && netscape.security) {
netscape.security.PrivilegeManager.enablePrivilege ("UniversalXPConnect");
}
// Copy the selected content to the clipboard
// Works in Firefox and in Safari before version 5
success = document.execCommand ("copy", false, null);
}
catch (e) {
success = false;
}
// remove the temporary element
document.body.removeChild (forExecElement);
}
if (success) {
alert ("The text is on the clipboard, try to paste it!");
}
else {
alert ("Your browser doesn't allow clipboard access!");
}
}
function CreateElementForExecCommand (textToClipboard) {
var forExecElement = document.createElement ("div");
// place outside the visible area
forExecElement.style.position = "absolute";
forExecElement.style.left = "-10000px";
forExecElement.style.top = "-10000px";
// write the necessary text into the element and append to the document
forExecElement.textContent = textToClipboard;
document.body.appendChild (forExecElement);
// the contentEditable mode is necessary for the execCommand method in Firefox
forExecElement.contentEditable = true;
return forExecElement;
}
function SelectContent (element) {
// first create a range
var rangeToSelect = document.createRange ();
rangeToSelect.selectNodeContents (element);
// select the contents
var selection = window.getSelection ();
selection.removeAllRanges ();
selection.addRange (rangeToSelect);
}
總結:
思路新奇,長姿勢了