Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyohei8/1f3992f956f790948072b08a196255f5 to your computer and use it in GitHub Desktop.
Save kyohei8/1f3992f956f790948072b08a196255f5 to your computer and use it in GitHub Desktop.
コピー to クリップボードについて.md

コピー to クリップボードについて

Chrome 43、Fx 41、IE10、iOS 10 以上で対応している

iOSはちょっと特殊なので以下のような処理は必要

前提条件

  • <input>,<textarea>からのみコピー可能
  • それ以外はcontenteditable属性を付ける必要がある
  • readonlyであってはいけない
  • テキストは選択状態である

実装について 【iOS以外】

  • 要素を選択してコピーを実行でOK
el.select();
document.execCommand('copy');

実装について 【iOS】

  • コピーしたいテキストを<input>および<textarea>につける
  • contenteditableおよびreadonlyの値を一時的に保持
  • 上記の値を変更 contenteditable -> trueへ、readonly -> false
  • rangeオブジェクトを生成し、該当の要素を選択
const range = document.createRange();
range.selectNodeContents(el);
  • テキストを選択する
const s = window.getSelection();
s.removeAllRanges();
s.addRange(range);
  • contenteditableおよびreadonlyの値をもとに戻す
  • コピーを実行
document.execCommand('copy');
  • フォーカス状態が残ってしまうので、その後にフォーカスを外すこと
s.removeAllRanges();

その他注意

  • iOSはinputのwidth, heightが1px以上必要みたい。その上でopacity: 0でも大丈夫そう
  • display: none, visibillty: hiddenはダメだった。

参考

https://stackoverflow.com/questions/34045777/copy-to-clipboard-using-javascript-in-ios

要素を生成して、削除するやりかた https://qiita.com/simiraaaa/items/2e7478d72f365aa48356

デモ

https://codepen.io/kyohei8/full/mxbgGm/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment