復(fù)制
- 文本復(fù)制( navigator.clipboard.writeText() )
let text = "123"
navigator.clipboard.writeText(text).then(() => {
ElMessage.success('復(fù)制成功')
});
- Dom元素復(fù)制-Html( navigator.clipboard.write() )
const shareRef = ref() //獲取Dom元素
// 新標(biāo)準(zhǔn) 注意此處是異步的
try {
const item = new window.ClipboardItem({
"text/html": new Blob([shareRef.value.innerHTML], { type: "text/html" })
});
await navigator.clipboard.write([item]).then(function() {
ElMessage.success('復(fù)制成功')
}, function(err) {
ElMessage.error('復(fù)制失敗')
console.error('err: ', err);
})
} catch (error) {
ElMessage.error('復(fù)制失敗')
}
獲取粘貼剪貼板的內(nèi)容(監(jiān)聽addEventListener)
if(inputRef.value) {
inputRef.value.addEventListener('paste', async (event:any) => {
// 在這里編寫你想在粘貼時(shí)執(zhí)行的代碼
// alert('內(nèi)容已粘貼!');
// 1.可以通過navigator.clipboard.readText()獲取粘貼板的內(nèi)容
navigator.clipboard.readText().then(clipText => {
console.log('粘貼的文本內(nèi)容:', clipText);
}).catch(error => {
console.error('讀取剪貼板失敗:', error);
});
// 2.可以通過event.clipboardData.getData('text')獲取粘貼板的內(nèi)容
var pastedData = event.clipboardData.getData('text');
console.log(pastedData);
});
}
- Html--(注意:html片段直接在input輸入框中粘貼不上,需要手動(dòng)賦值)
if(inputRef.value) {
inputRef.value.addEventListener('paste', async (event:any) => {
// 異步
try {
const clipboardItems = await navigator.clipboard.read();
for (const clipboardItem of clipboardItems) {
for (const type of clipboardItem.types) {
const blob = await clipboardItem.getType(type);
const html = await blob.text()
// const tempHtml = html.replace(/<[^>]+>/g, '\n');
const tempHtml1 = html.replace(/<\/d[^>]+>/g, '\n');
const tempHtml2 = tempHtml1.replace(/<[^>]+>/g, '');
console.log(html) //<div>123</div><div>456</>
console.log(tempHtml2) // 123\n456
// console.log(URL.createObjectURL(blob));
inputValue.value = tempHtml2 // 賦值
}
}
} catch (err:any) {
console.error(err.name, err.message);
}
});
}