注意第一部分的內容不兼容Safari,全兼容的請使用第二部分方法
第一部分
查看demo請點 這里。
原生js復制指定內容到剪切板,超簡單的實現方式,
實現思路如下:
1.創建一個input,把想要復制的內容賦值到input的value上;
2. 把這個input插入到body內;
3.獲取這個input,對它執行選中;
4.執行documen的copy事件;
5,刪除剛剛插入的input。
代碼如下:
html:
<button id="btn">復制</button>
js:
// 復制的方法
function copyText(text, callback){ // text: 要復制的內容, callback: 回調
var tag = document.createElement('input'); 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)} } // 點擊按鈕調用復制
document.getElementById('btn').onclick = function (){ copyText( '123456', function (){console.log('復制成功')}) }
直接復制下來看效果的:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<body>
<button id="btn">復制</button>
<script type="text/javascript">
// 復制的方法
function copyText(text, callback){ // text: 要復制的內容, callback: 回調
var tag = document.createElement('input'); 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)} } // 點擊按鈕調用復制
document.getElementById('btn').onclick = function (){ copyText( '123456', function (){console.log('復制成功')}) } </script>
</body>
</html>
第二部分
使用這個:https://github.com/zenorocha/clipboard.js
引入這個插件的js,
使用方法,去看他的demo吧, 拜拜!
(完)