ものすごく癖が強かったのでまとめた。
IE は死んだと思っているので IE での動作は確認していないけどきっと動かないと思う。
サンプルをhttps://hondash.github.io/sandbox/javascript/copy-to-clipboard/に置いた
範囲選択の方法は確認した限りでは多分3つある。
また、display: none;
、visibility: hidden;
ではコピーできないっぽい。
select()
input, textarea などの HTMLInputElement で使える select()
を呼ぶ。ただし、divなどでは使えない。
document.getElementById("textarea").select()
ぱっと見では楽だけど、対応していないブラウザがあったりするので使わないほうが良さそう。iOS とか iOS とか…。
setSelectionRange()
input, textarea などの HTMLInputElement で使える setSelectionRange()
を呼ぶ。ただし、divなどでは使えない。
const target = document.getElementById("input")
const length = target.value.length
target.focus()
target.setSelectionRange(0, length)
フォーカスさせないとコピーの挙動がおかしくなるので注意。
これは最新の iPhone では動いた。
window.getSelection().addRange(range)
汎用的に使えるけど、動かない場合もある
// 選択範囲を解除
window.getSelection().removeAllRanges()
// Rangeの指定
const range = document.createRange()
const referenceNode = document.getElementById("textarea")
range.selectNode(referenceNode)
// 範囲選択
window.getSelection().addRange(range)
window.getSelection().removeAllRanges()
を最初に呼ばないと二回目以降の挙動がおかしくなるので注意。
これも iPhone で反応しないことがあったので要注意。
参考
- https://developer.mozilla.org/ja/docs/Web/API/HTMLInputElement/setSelectionRange
- https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select
- https://developer.mozilla.org/ja/docs/Web/API/Selection/addRange