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

原生js實現(xiàn)點(diǎn)擊按鈕復(fù)制內(nèi)容到剪切板

 更新時間:2020年11月19日 11:05:38   作者:weixin_44953227  
這篇文章主要為大家詳細(xì)介紹了原生js實現(xiàn)點(diǎn)擊按鈕復(fù)制內(nèi)容到剪切板,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了js點(diǎn)擊按鈕復(fù)制內(nèi)容到剪切板的具體代碼,供大家參考,具體內(nèi)容如下

效果圖

上代碼

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>
  .divBox {
    width: 500px;
    margin: 100px auto;
    display: flex;
  }

  .popupStyle {
    display: none;
    width: 160px;
    background-color: rgb(85, 85, 85);
    color: aqua;
    text-align: center;
    border-radius: 6px;
    padding: 8px 0;
    position: fixed;
    z-index: 1;
    top: 2%;
    left: 50%;
    margin-left: -80px;
  }
</style>
<body>
  <div class="divBox">
    <div id="div">這是要復(fù)制的div內(nèi)容</div>
    <a href="#" onclick="handleDivCopy()">點(diǎn)擊復(fù)制</a>
  </div>
  <div class="divBox">
    <textarea id="textarea">Hello,World</textarea>
    <a href="#" onclick="handleCopy()">點(diǎn)擊復(fù)制</a>
  </div>
  <script>
    
    // 復(fù)制 div 內(nèi)容
    function handleDivCopy() {
      const div = document.getElementById("div");
      const input = document.createElement("input");
      document.body.appendChild(input);
      input.value = div.innerText;
      input.select();
      
      try {
        if (document.execCommand("copy", false)) {
          handleDomMsg("div 內(nèi)容復(fù)制成功");
        } else {
          handleDomMsg("div 內(nèi)容復(fù)制失敗");
        }
      } catch (error) {
        console.log(error, "error")
      } finally {
        input.remove();
      }
    };
    
    // 復(fù)制輸入框內(nèi)容
    function handleCopy() {
      const textarea = document.getElementById("textarea");
      textarea.select();
      try {
        if (document.execCommand("copy", false)) {
          handleDomMsg("輸入框內(nèi)容復(fù)制成功");
        } else {
          handleDomMsg("輸入框內(nèi)容復(fù)制失敗");
        }
      } catch (error) {
        console.log(error, "error")
      }
    };


    // DOM 彈窗
    function handleDomMsg(message) {
      const div = document.createElement("div");
      document.body.appendChild(div);
      div.innerHTML = message || "this is a Message";
      div.className = "popupStyle";
      div.style.display = "block";

      setTimeout(() => {
        div.remove();
      }, 1000);
    }

  </script>
</body>
</html>

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

相關(guān)文章

最新評論