LoginSignup
0
1

More than 1 year has passed since last update.

クリックでリンクをコピー 【HTML・CSS・JavaScript】

Last updated at Posted at 2022-08-06

完成形はこちら↓

ezgif.com-gif-maker (4).gif
※アイコンはfontawesome v5を使用しています。

html
<div class="text-link">
 <div class="copy-link">
    <input type="text" class="link" value="ここにURLを入れてね">
    <button type="button">
      <i class="fas fa-clone"></i>
    </button>
   </div>
</div>
scss
.copy-link {
  position: relative;
  padding: 10px;
  background: #fff;
  border: 1px solid #ddd;
  border-radius: 10px;
  display: flex;

  input {
    padding: 10px;
    font-size: 18px;
    color: #555;
    border: none;
    outline: none;
    width: 100%;
  }

  button {
    padding: 10px;
    background: var(--main-color-dark);
    font-size: 18px;
    color: #fff;
    outline: none;
    border: none;
    border-radius: 10px;
    cursor: pointer;

    &:active {
      background: var(--main-color-light);
    }

    &::before {
      content: "Copied!";
      position: absolute;
      top: -50px;
      right: 0px;
      background: var(--main-color-dark);
      border-radius: 20px;
      padding: 9px 10px;
      font-size: 14px;
      display: none;
    }

    &::after {
      content: "";
      position: absolute;
      top: -20px;
      right: 25px;
      width: 10px;
      height: 10px;
      background: var(--main-color-dark);
      transform: rotate(45deg);
      display: none;
    }
  }

  &.active button::after,
  &.active button::before {
    display: block;
  }
}
JavaScript

let copyText = document.querySelector(".copy-link");

copyText.querySelector("button").addEventListener("click", function() {
//アイコンをクリックしたら、下記を実行
 let input = copyText.querySelector("input.link");
 input.select(); //select()メソッドはinput or textareaのテキストを選択します
 document.execCommand("copy") //document.execCommand("copy")は任意の値をクリップボードにコピーするJSのコマンド
 copyText.classList.add("active"); //activeクラスを付与し、吹き出しを表示させます
 window.getSelection().removeAllRanges(); //range(範囲)を削除します

 setTimeout(function() {
  copyText.classList.remove("active");
 }, 2500)  //2.5秒後に吹き出しを非表示にします
})

selection・rangeについては下記の記事に詳しく説明されています
 ▶︎ https://ja.javascript.info/selection-range

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1