将文本复制到剪贴板

创建于 2024-12-03 / 22
字体: [默认] [大] [更大]

了解如何使用 JavaScript 将文本复制到剪贴板。


单击按钮从文本字段中复制文本。


将文本复制到剪贴板

步骤 1) 添加 HTML:

实例

<!-- 文本字段 -->
<input type="text" value="Hello World" id="myInput">

<!-- 用于复制文本的按钮 -->
<button onclick="myFunction()">Copy text</button>
第 2 步)添加 JavaScript:

实例

function myFunction() {
  /* 获取文本字段 */
  var copyText = document.getElementById("myInput");

  /* Select the text field */
  copyText.select();
  copyText.setSelectionRange(0, 99999); /*对于移动设备*/

  /* 复制文本字段内的文本 */
  document.execCommand("copy");

  /* 提醒复制的文本 */
  alert("Copied the text: " + copyText.value);
} 亲自试一试 »

注释: The document.execCommand() method is not supported in IE8 and earlier.



在工具提示中显示复制的文本

添加 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;
} 亲自试一试 »

0 人点赞过