如何將文本復制到剪貼板
學習如何使用 JavaScript 將文本復制到剪貼板。
單擊該按鈕可從文本字段復制文本。
將文本復制到剪貼板
第一步 - 添加 HTML:
<!-- 文本字段 --> <input type="text" value="Hello World" id="myInput"> <!-- 用于復制文本的按鈕 --> <button onclick="myFunction()">復制文本</button>
第二步 - 添加 JavaScript:
function myFunction() { // 獲取文本字段 var copyText = document.getElementById("myInput"); // 選擇文本字段 copyText.select(); copyText.setSelectionRange(0, 99999); // 針對移動設備 // 復制文本字段內的文本 navigator.clipboard.writeText(copyText.value); // 提醒復制的文本 alert("Copied the text: " + copyText.value); }
在工具提示中顯示復制的文本
添加 CSS:
.tooltip { position: relative; display: inline-block; } .tooltip .tooltiptext { visibility: hidden; width: 140px; background-color: #555; color: #fff; text-align: center; border-radius: 6px; padding: 5px; position: absolute; z-index: 1; bottom: 150%; left: 50%; margin-left: -75px; opacity: 0; transition: opacity 0.3s; } .tooltip .tooltiptext::after { content: ""; position: absolute; top: 100%; left: 50%; margin-left: -5px; border-width: 5px; border-style: solid; border-color: #555 transparent transparent transparent; } .tooltip:hover .tooltiptext { visibility: visible; opacity: 1; }