Bagaimana untuk menyalin teks ke papan klip

Belajar bagaimana untuk menyalin teks ke papan klip menggunakan JavaScript.

Klik butang ini untuk menyalin teks daripada medan teks.

Salin teks ke papan klip

Langkah pertama - Tambahkan 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;
{}

亲自试一试