LoginSignup
1
2

More than 3 years have passed since last update.

【jQuery】クリックでテキストをコピー

Last updated at Posted at 2020-01-06

前提

jQueryを使っているのでCDNを読み込むなど、
jQueryが利用できるようにしてください。

コード

<h2>
  <span>コピーしないテキスト</span>
  <span class="text">コピーするテキスト</span>
  <span>コピーしないテキスト</span>
  <span class="copy-text-btn">【ここをクリックでテキストをコピー】</span>
</h2>
textCopy.js
window.addEventListener('load', function(){
  $('.copy-text-btn').on('click',function(){
    var textElem = $(this).parent().find('.text');
    window.getSelection().selectAllChildren(textElem[0]);
    document.execCommand("copy");
    window.alert("テキストをコピーしました!");
  });
});

動作実演GIF

2020-01-07 01.05.07.gif

1
2
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
1
2