ZeroClipboard.js 是相當老牌的字串複製/貼上外掛。官方目前已推進到 2.x,但 2.x 不支援 IE9 以下的瀏覽器;如果需要向下相容,就得停留在 1.x 分支。本文示範的是最初的 1.0.7 版本,它支援 IE7 與 IE8,重點則是:如何只靠一個 Flash 物件,服務頁面上多個複製按鈕。
一般要複製某個欄位時,多數人會這樣建立物件:
<div id="J_pop_share"> <input id="J_video_iframe1" value="<iframe src="https://caibaojian.com/book/"></iframe>" /> <button id="J_copy_btn1">複製</button> </div>
var clip = null; // ZeroClipboard.Client 對象
var current_id = null; // 當前所在的文本元素 id
// 指定 ZeroClipboard.swf 位置
ZeroClipboard.setMoviePath(location.protocol + "//club.pcauto.com.cn/js/ZeroClipboard.swf");
clip = new ZeroClipboard.Client(); // 創建 ZeroClipboard.Client 對象
clip.setHandCursor(true); // 鼠標移到元素上顯示手型
clip.glue('J_copy_btn1', 'J_pop_share');
clip.setText($('#J_video_iframe1').val());
// 添加複製成功之後的操作
clip.addEventListener('complete', function () {
alert('復制成功');
});
看到四組輸入框與按鈕,很容易直覺地以為要 new 出四個 Flash 物件。其實還有另一條路:沿用同一個 Flash,在滑鼠移進不同按鈕時,動態改變它的位置與要複製的文字內容。
HTML 結構如下:
<div id="J_pop_share">
<div>
<input id="J_video_iframe1" value="<iframe src="https://caibaojian.com/book/"></iframe>" />
<button id="J_copy_btn1" class="btn-copy-text">複製</button>
</div>
<div>
<input id="J_video_iframe2" value="<iframe src="https://caibaojian.com/book/"></iframe>" />
<button id="J_copy_btn2" class="btn-copy-text">複製</button>
</div>
<div>
<input id="J_video_iframe3" value="<iframe src="https://caibaojian.com/book/"></iframe>" />
<button id="J_copy_btn3" class="btn-copy-text">複製</button>
</div>
<div>
<input id="J_video_iframe4" value="<iframe src="https://caibaojian.com/book/"></iframe>" />
<button id="J_copy_btn4" class="btn-copy-text">複製</button>
</div>
</div>
JavaScript 部分,在上面那段程式碼之後追加:
// 為每個複製按鈕綁定移入事件
$(".btn-copy-text").each(function (i) {
var index = i + 1;
$(this).on('mouseover', function () {
var button_id = $(this).attr('id'); // 複製 div 的 id
var text_id = 'J_video_iframe' + index; // 要複製的元素 id
move_swf(text_id, button_id);
});
});
// 移動浮動 flash div 到指定位置,只需一個 flash 即可在多處實現複製
function move_swf(text_id, button_id) {
// 重新指定 flash 浮動 div 位置
clip.reposition(button_id, 'J_pop_share');
clip.setText($('#' + text_id).val());
}
使用 ZeroClipboard.js 時難免遇到各種詭異 Bug。我曾經在 IE 上碰到這樣的狀況:內容放在彈窗裡,複製第一個正常,複製第二個卻報「沒有這個對象」。反覆排查很久都找不到原因,後來把彈窗改成不隱藏就完全正常,於是判斷問題出在 Flash 物件的隱藏與顯示上。
解法是把原本的 display 隱藏,改為絕對定位並推到 left:-9999px;要顯示時再把 left 設回正確數值,錯誤便不再出現。歸根究柢,Flash 物件在具備實際尺寸與座標時才能被正確操作,用 display:none 藏起來會讓它的位置資訊失效。