テキストをクリップボードにコピーする方法

JavaScriptを使用してテキストをクリップボードにコピーする方法を学びます。

このボタンをクリックしてテキストフィールドのテキストをコピーできます。

テキストをクリップボードにコピーします

第1歩 - HTMLを追加:

<!-- テキストフィールド -->
<input type="text" value="Hello World" id="myInput">
<!-- テキストをコピーするボタン -->
<button onclick="myFunction()">テキストをコピー</button>

第2ステップ - JavaScriptを追加:

function myFunction() {
  // テキストフィールドを取得
  var copyText = document.getElementById("myInput");
  // テキストフィールドを選択
  copyText.select();
  copyText.setSelectionRange(0, 99999); // モバイルデバイス用
   // テキストフィールド内のテキストをコピー
  navigator.clipboard.writeText(copyText.value);
  // コピーされたテキストを通知
  alert("コピーされたテキスト: " + 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;
}

自分で試してみる