欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

js?剪切、復(fù)制、粘貼功能實(shí)現(xiàn)

 更新時(shí)間:2023年05月02日 16:48:23   作者:huangpb0624  
Navigator.clipboard?API可以用來(lái)訪問(wèn)系統(tǒng)剪貼板,可以實(shí)現(xiàn)【剪切、復(fù)制、粘貼】功能。該?API?被設(shè)計(jì)用來(lái)取代使用?document.execCommand()?的剪貼板訪問(wèn)方式,不兼容?IE

針對(duì)現(xiàn)代瀏覽器實(shí)現(xiàn)(Navigator.clipboard)

Navigator.clipboard API可以用來(lái)訪問(wèn)系統(tǒng)剪貼板,可以實(shí)現(xiàn)【剪切、復(fù)制、粘貼】功能。該 API 被設(shè)計(jì)用來(lái)取代使用 document.execCommand() 的剪貼板訪問(wèn)方式,不兼容 IE。

使用 Navigator.clipboard API時(shí)會(huì)彈出用戶授權(quán)彈窗。如果用戶沒有授予權(quán)限,則不允許讀取或更改剪貼板內(nèi)容。

let clipBoard = navigator.clipboard;
// 寫入文本至操作系統(tǒng)剪貼板
clipBoard.writeText('你好').then(() => {
  this.$message.success('復(fù)制成功!')
})
// 寫入任意數(shù)據(jù)(比如圖片)至操作系統(tǒng)剪貼板用 clipBoard.write()
// 從剪貼板讀取文本
clipBoard.readText().then(clipText => {
  console.log(clipText);
})
// 從剪貼板讀取數(shù)據(jù)(比如圖片)用 clipBoard.read()

針對(duì)舊版本瀏覽器實(shí)現(xiàn)(document.execCommand)
document.execCommand 針對(duì)可編輯內(nèi)容區(qū)域提供了很多有用的 API,包括其中的【剪切、復(fù)制、粘貼】功能。

MDN 寫到 document.execCommand 方法已廢棄。

document.execCommand 的復(fù)制有個(gè)前提,必須先選中內(nèi)容,但有時(shí)候我們要實(shí)現(xiàn)的效果是沒有選中這個(gè)動(dòng)作的,比如在手機(jī)號(hào)后面有個(gè)“復(fù)制”按鈕,點(diǎn)擊按鈕就直接復(fù)制了手機(jī)號(hào),這里我們有2種方法實(shí)現(xiàn):

方法1:在 body 動(dòng)態(tài)追加一個(gè)隱藏的文本域,再用 select() 方法選中里面的內(nèi)容,接著 document.execCommand('copy') 進(jìn)行復(fù)制。

function copyText (text) {
  $('body').append(`<textarea id="iclip-container" value="${text}">${text}</textarea>`);
  $('#iclip-container').select();
  if (document.execCommand('copy', false, null)) {
    $('#iclip-container').remove();
    alert('復(fù)制成功!')
  }
}

方法2:監(jiān)聽 copy 事件,在事件回調(diào)里添加要復(fù)制的內(nèi)容。

function copyText (text) {
  const copy = function(event) {
      let clipboardData = event.clipboardData || window.clipboardData;
      clipboardData.setData('text/plain', text);
      event.preventDefault();
  };
  document.addEventListener('copy', copy);
  document.execCommand('copy');
  document.removeEventListener('copy', copy);
  this.$message.success('復(fù)制成功!');
},

剪切、復(fù)制、粘貼事件

可以給元素綁定 cut、copy、paste 事件監(jiān)聽剪切、復(fù)制、粘貼行為。

// 可以監(jiān)聽 cut 事件對(duì)剪切內(nèi)容進(jìn)行修改
const source = document.querySelector('div.source');
source.addEventListener('cut', (event) => {
    const selection = document.getSelection();
    event.clipboardData.setData('text/plain', selection.toString().toUpperCase());
    selection.deleteFromDocument();
    event.preventDefault();
});

到此這篇關(guān)于js 剪切、復(fù)制、粘貼功能實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)js 剪切、復(fù)制、粘貼內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論