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

js實(shí)現(xiàn)復(fù)制粘貼的兩種方法

 更新時(shí)間:2020年12月04日 13:56:54   作者:后青春詩ing  
這篇文章主要為大家詳細(xì)介紹了js實(shí)現(xiàn)的兩種方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了js實(shí)現(xiàn)復(fù)制粘貼的具體代碼,供大家參考,具體內(nèi)容如下

一、前沿

界面需要復(fù)制功能,所以就寫了一個(gè)作為簡單記錄

二、方法、推薦第二種。

1、第一種方法

1)、通過 document.execCommand('copy')
2)、前端代碼如下:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>constructor-nodelist</title>
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" />

</head>
<body>
<button class="copy_file" onclick="copyText('copy_file')">點(diǎn)我復(fù)制</button>
<a id="copy_file" href="復(fù)制內(nèi)容" ></a>
<script type="text/javascript" src="https://cdn.bootcss.com/sweetalert/1.1.3/sweetalert.min.js"></script>
<script>
function copyText(str_file) {
 const btn = document.querySelector('.'+str_file);
 var copy_val = document.getElementById(str_file)
 var copy_file = copy_val.getAttribute("href");
 btn.addEventListener('click',() => {
  const input = document.createElement('input');
  document.body.appendChild(input);
  input.setAttribute('value', copy_file);
  input.select();
  if (document.execCommand('copy')) {
   document.execCommand('copy');
   swal("復(fù)制成功!","success");
  }
  document.body.removeChild(input);
 })
}

</script>
</body>

3)、總結(jié):主要是通過 class和id 來復(fù)制 a標(biāo)簽中的 href,把復(fù)制好的內(nèi)容放到 生成的input標(biāo)簽中,然后復(fù)制結(jié)束把 input標(biāo)簽給remove,這個(gè)你復(fù)制內(nèi)容自行發(fā)揮,和修改 js。
4)、問題:第一次點(diǎn)擊不生效,需要點(diǎn)擊兩次,暫時(shí)不解決

2、第二種方法

1)、通過 ClipboardJS 來實(shí)現(xiàn) 內(nèi)容的復(fù)制,推薦這個(gè)
2)、git地址:clipboardjs
3)、前端代碼如下:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
 <!-- 請自行去git項(xiàng)目下載 js-->
 <script src="./clipboard.min.js"></script>
 <link rel="stylesheet" />
 <script type="text/javascript" src="https://cdn.bootcss.com/sweetalert/1.1.3/sweetalert.min.js"></script>
</head>
<body>

<button id="btn" data-clipboard-text="str_555" onclick="copyText()">
 <span>Copy</span>
</button>
</body>
</html>

<script>
function copyText() {
 var btn = document.getElementById('btn');
 console.log(btn);
  var clipboard = new ClipboardJS(btn);
<!--  var clipboard = new ClipboardJS(btn, {-->
<!--   container: document.getElementById('btn')-->
<!--  });--> 如果你的項(xiàng)目是 bootstrap框架,請使用這個(gè)
  clipboard.on('success', function(e) {
   console.log(e);
   swal("復(fù)制成功!","success");
   clipboard.destroy();
  });

  clipboard.on('error', function(e) {
   console.log(e);
   swal("復(fù)制失敗","error");
   clipboard.destroy();
  });
}
</script>

3)、總結(jié):請一定要仔細(xì)閱讀 文檔。這個(gè)項(xiàng)目還是非常強(qiáng)大的,強(qiáng)烈推薦這個(gè)。

4)、問題:也是遇到了 第一次復(fù)制不生效的問題,暫時(shí)不解決了。

三、總結(jié)

1、都遇到了 第一次復(fù)制不生效的問題,后續(xù)解決把,都采用了 sweetalert 。
2、個(gè)人都只在 谷歌和火狐瀏覽器實(shí)驗(yàn)了,都可以用,如果其他瀏覽器版本不能用,請自行查閱其他文章,歡迎溝通、指正。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

您可能感興趣的文章:

相關(guān)文章

最新評論