JavaScript複製內容到剪貼板

原文連接:github.com/axuebin/art…javascript


最近一個活動頁面中有一個小需求,用戶點擊或者長按就能夠複製內容到剪貼板,記錄一下實現過程和遇到的坑。html

常見方法

查了一下萬能的Google,如今常見的方法主要是如下兩種:java

  • 第三方庫:clipboard.js
  • 原生方法:document.execCommand()

分別來看看這兩種方法是如何使用的。ios

clipboard.js

這是clipboard的官網:clipboardjs.com/,看起來就是這麼的簡單。git

引用

直接引用: <script src="dist/clipboard.min.js"></script>github

包: npm install clipboard --save ,而後 import Clipboard from 'clipboard';npm

使用

從輸入框複製

如今頁面上有一個 <input> 標籤,咱們須要複製其中的內容,咱們能夠這樣作:瀏覽器

<input id="demoInput" value="hello world">
<button class="btn" data-clipboard-target="#demoInput">點我複製</button>
複製代碼
import Clipboard from 'clipboard';
const btnCopy = new Clipboard('btn');
複製代碼

注意到,在 <button> 標籤中添加了一個 data-clipboard-target 屬性,它的值是須要複製的 <input>id,顧名思義是從整個標籤中複製內容。app

直接複製

有的時候,咱們並不但願從 <input> 中複製內容,僅僅是直接從變量中取值。若是在 Vue 中咱們能夠這樣作:函數

<button class="btn" :data-clipboard-text="copyValue">點我複製</button>
複製代碼
import Clipboard from 'clipboard';
const btnCopy = new Clipboard('btn');
this.copyValue = 'hello world';
複製代碼

事件

有的時候咱們須要在複製後作一些事情,這時候就須要回調函數的支持。

在處理函數中加入如下代碼:

// 複製成功後執行的回調函數
clipboard.on('success', function(e) {
    console.info('Action:', e.action); // 動做名稱,好比:Action: copy
    console.info('Text:', e.text); // 內容,好比:Text:hello word
    console.info('Trigger:', e.trigger); // 觸發元素:好比:<button class="btn" :data-clipboard-text="copyValue">點我複製</button>
    e.clearSelection(); // 清除選中內容
});

// 複製失敗後執行的回調函數
clipboard.on('error', function(e) {
    console.error('Action:', e.action);
    console.error('Trigger:', e.trigger);
});
複製代碼

小結

文檔中還提到,若是在單頁面中使用 clipboard ,爲了使得生命週期管理更加的優雅,在使用完以後記得 btn.destroy() 銷燬一下。

clipboard 使用起來是否是很簡單。可是,就爲了一個 copy 功能就使用額外的第三方庫是否是不夠優雅,這時候該怎麼辦?那就用原生方法實現唄。

document.execCommand()方法

先看看這個方法在 MDN 上是怎麼定義的:

which allows one to run commands to manipulate the contents of the editable region.

意思就是能夠容許運行命令來操做可編輯區域的內容,注意,是可編輯區域

定義

bool = document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)

方法返回一個 Boolean 值,表示操做是否成功。

  • aCommandName :表示命令名稱,好比: copy, cut 等(更多命令見命令);
  • aShowDefaultUI:是否展現用戶界面,通常狀況下都是 false
  • aValueArgument:有些命令須要額外的參數,通常用不到;

兼容性

這個方法在以前的兼容性實際上是不太好的,可是好在如今已經基本兼容全部主流瀏覽器了,在移動端也可使用。

兼容性

使用

從輸入框複製

如今頁面上有一個 <input> 標籤,咱們想要複製其中的內容,咱們能夠這樣作:

<input id="demoInput" value="hello world">
<button id="btn">點我複製</button>
複製代碼
const btn = document.querySelector('#btn');
btn.addEventListener('click', () => {
	const input = document.querySelector('#demoInput');
	input.select();
	if (document.execCommand('copy')) {
		document.execCommand('copy');
		console.log('複製成功');
	}
})
複製代碼

其它地方複製

有的時候頁面上並無 <input> 標籤,咱們可能須要從一個 <div> 中複製內容,或者直接複製變量。

還記得在 execCommand() 方法的定義中提到,它只能操做可編輯區域,也就是意味着除了 <input><textarea> 這樣的輸入域之外,是沒法使用這個方法的。

這時候咱們須要曲線救國。

<button id="btn">點我複製</button>
複製代碼
const btn = document.querySelector('#btn');
btn.addEventListener('click',() => {
	const input = document.createElement('input');
	document.body.appendChild(input);
 	input.setAttribute('value', '據說你想複製我');
	input.select();
	if (document.execCommand('copy')) {
		document.execCommand('copy');
		console.log('複製成功');
	}
    document.body.removeChild(input);
})
複製代碼

算是曲線救國成功了吧。在使用這個方法時,遇到了幾個坑。

遇到的坑

在Chrome下調試的時候,這個方法時完美運行的。而後到了移動端調試的時候,坑就出來了。

對,沒錯,就是你,ios。。。

  1. 點擊複製時屏幕下方會出現白屏抖動,仔細看是拉起鍵盤又瞬間收起

    知道了抖動是因爲什麼產生的就比較好解決了。既然是拉起鍵盤,那就是聚焦到了輸入域,那隻要讓輸入域不可輸入就行了,在代碼中添加 input.setAttribute('readonly', 'readonly'); 使這個 <input> 是隻讀的,就不會拉起鍵盤了。

  2. 沒法複製

    這個問題是因爲 input.select() 在ios下並無選中所有內容,咱們須要使用另外一個方法來選中內容,這個方法就是 input.setSelectionRange(0, input.value.length);

完整代碼以下:

const btn = document.querySelector('#btn');
btn.addEventListener('click',() => {
	const input = document.createElement('input');
    input.setAttribute('readonly', 'readonly');
    input.setAttribute('value', 'hello world');
    document.body.appendChild(input);
	input.setSelectionRange(0, 9999);
	if (document.execCommand('copy')) {
		document.execCommand('copy');
		console.log('複製成功');
	}
    document.body.removeChild(input);
})
複製代碼

總結

以上就是關於JavaScript如何實現複製內容到剪貼板,附上幾個連接:

execCommand MDN

execCommand兼容性

clipboard.js

相關文章
相關標籤/搜索