一個(gè)不分離項(xiàng)目的緊急需求, 需要添加一個(gè)復(fù)制功能, 作為一個(gè)小菜鳥(niǎo), 自己寫(xiě)肯定寫(xiě)不出, 也記不住那么多方法, 之前分離項(xiàng)目, npm install 安裝插件就好了, 但是不分離項(xiàng)目不好找對(duì)應(yīng)插件, 期望使用原生js
- 在經(jīng)過(guò)百度, CSDN, 博客園這些文抄公之后, 歷經(jīng)九九八十一難, 終于找到了, 特此在這里記錄
//點(diǎn)擊文本框復(fù)制其內(nèi)容到剪貼板上方法
function copyToClipboard(str) {
var cinput = document.createElement('textarea'); // 動(dòng)態(tài)創(chuàng)建textarea元素
cinput.value = str; // 把需要復(fù)制的內(nèi)容賦值到textarea的vlaue上
cinput.setAttribute('readOnly', 'true');
//注意大小寫(xiě),不寫(xiě)的話(huà)手機(jī)端會(huì)自動(dòng)彈出輸入框
document.body.appendChild(cinput); // 把創(chuàng)建的textarea元素添加進(jìn)body元素內(nèi)
cinput.select(); // 選擇對(duì)象
document.execCommand("Copy"); // 執(zhí)行瀏覽器復(fù)制命令
cinput.className = 'oInput';
cinput.style.display = 'none';
cinput.style.opacity = '0';
alert("復(fù)制成功");
}
// 復(fù)制的方法
function copyText(text, callback){ // text: 要復(fù)制的內(nèi)容缕减, callback: 回調(diào)
var tag = document.createElement('textarea');
tag.setAttribute('id', 'cp_hgz_input');
tag.value = text;
document.getElementsByTagName('body')[0].appendChild(tag);
document.getElementById('cp_hgz_input').select();
document.execCommand('copy');
document.getElementById('cp_hgz_input').remove();
if(callback) {callback(text)}
}
方法都差不多, 起碼又用, 最后吐槽, 文抄公能不能抄點(diǎn)有用的, 也不管人家博主寫(xiě)的代碼有用沒(méi)用, 看到人家寫(xiě)了就往自己博客上套, 出錯(cuò)的地方也一樣.也不檢查或者自己運(yùn)行一下