Copy

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

詳しい導入事例は導入方法を参照してください。

クリックで任意の文字列をクリップボードにコピーする機能。

  • DEMO
テスト

使い方

トリガーとなる要素に+-.mod_copy-+のclass追加で内包する文字列をコピーする。
コピー時にウィンドウ下部にスナックバーを表示。

[data-copy]属性を追加すると内包する文字列ではなく、属性に入れた文字列をコピーします。

  • HTML
  • CSS
  • Script

  
.mod_copy {cursor: pointer;}
#mod_copy-alert {
  width: 100%;
  height: 50px;
  padding: 0 24px;
  line-height: 50px;
  background: rgb(0 0 0 / .8);
  color: var(--bg-paper);
  box-sizing: border-box;
  position: fixed;
  bottom: 0;
  left: 0;
  display: none;
}
.mod_copy-alert-txt {
  display: flex;
  gap: 8px;
}
.mod_copy-alert-tar {
  max-width: calc(100% - 20em - 8px);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  opacity: .8;
}
$bd.on('click','.mod_copy',function(){
  if($('#mod_copy-alert')[0]){$('#mod_copy-alert').remove();}

  let $copyarea = $('<textarea></textarea>');
  let copyTxt = $(this).data('copy');
  if(copyTxt == undefined){copyTxt = $(this).text();}
  let $copyalert = $('<div id="mod_copy-alert"><p class="mod_copy-alert-txt"><span class="mod_copy-alert-tar">[ '+copyTxt+' ]</span>クリップボードにコピーしました</p></div>');

  $copyarea.text(copyTxt);
  $bd.append($copyarea).append($copyalert);
  $copyarea.select();
  document.execCommand('copy');
  $copyarea.remove();

  $copyalert.fadeIn();
  setTimeout(function(){
    $copyalert.fadeOut().queue(function(){
      this.remove();
    });
  },1000);
});