JS實現(xiàn)復(fù)制指定文本功能
功能描述:
點擊按鈕,將指定文本復(fù)制到剪貼板。
示例如下:
點擊分享按鈕,將當(dāng)前條目鏈接復(fù)制到剪貼板。

功能實現(xiàn):
HTML部分:
<input type="text" id="copyVal" value="被復(fù)制內(nèi)容" />JS部分:
let input = document.getElementById('httpUrl');
input.select();
if(document.execCommand('copy')){
鏈接復(fù)制成功執(zhí)行
}else{
鏈接復(fù)制失敗執(zhí)行
}功能升級:
文本框不呈現(xiàn)給用戶,點擊對應(yīng)條目的復(fù)制按鈕,復(fù)制對應(yīng)文本內(nèi)容。
文本框內(nèi)容不呈現(xiàn)給用戶,有如下幾種方式:
1、display屬性值為none;
2、opacity屬性值為0;
3、不渲染該節(jié)點在DOM樹中;
4、內(nèi)容存儲在JS中;
但是,要使document.execCommand(‘copy’)生效,要滿足如下幾點:
1、input框不能有disabled屬性
2、width和height不能為0
3、input框不能有hidden、display:none屬性
簡單來說,輸入框要在正常的編輯狀態(tài)下。
解決方式:
將input框設(shè)置屬性opacity:0,將輸入框的透明度設(shè)置為完全透明。設(shè)置屬性position:absolute,設(shè)置輸入框絕對定位,不占用文檔位置。
代碼示例:
HTML部分:
<input type="text" id="copyUrl" v-model="copyUrl"/>CSS部分:
#copyUrl{
position: absolute;
top: 0;
opacity: 0;
}JS部分:
let input = document.getElementById('copyUrl');
input.select();
if(document.execCommand('copy')){
document.execCommand('copy');
this.$message({
message: '鏈接已經(jīng)復(fù)制成功!',
type: 'success'
});
document.execCommand('copy');
}else{
this.$message({
message: '鏈接復(fù)制失??!',
type: 'error'
});
}點擊關(guān)注公眾號,查看更多內(nèi)容:
評論
圖片
表情
