如何将文本复制到剪贴板
学习如何使用 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; }