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

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

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

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

一、前沿

界面需要復制功能,所以就寫了一個作為簡單記錄

二、方法、推薦第二種。

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')">點我復制</button>
<a id="copy_file" href="復制內(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("復制成功!","success");
  }
  document.body.removeChild(input);
 })
}

</script>
</body>

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

2、第二種方法

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

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
 <!-- 請自行去git項目下載 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')-->
<!--  });--> 如果你的項目是 bootstrap框架,請使用這個
  clipboard.on('success', function(e) {
   console.log(e);
   swal("復制成功!","success");
   clipboard.destroy();
  });

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

3)、總結(jié):請一定要仔細閱讀 文檔。這個項目還是非常強大的,強烈推薦這個。

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

三、總結(jié)

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

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

您可能感興趣的文章:

相關(guān)文章

最新評論