<!-- data-copy の中身がそのままコピーされる --> <button type="button" class="bnto-cp1" data-bnto-copy data-copy="ここに書いた文字列がコピーされます"> <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><rect width="14" height="14" x="8" y="8" rx="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg> <span class="lb">テキストをコピー</span><span class="ok">コピーしました ✓</span> </button>
.bnto-cp1 { --c1: hsl(202 73% 50%); /* ボタン色 */ display: inline-flex; align-items: center; gap: 8px; padding: 12px 22px; background: var(--c1); color: #fff; border: none; border-radius: 12px; font: inherit; font-weight: 800; cursor: pointer; transition: transform .15s, background .3s; } .bnto-cp1:active { transform: scale(.95); } .bnto-cp1 .ok { display: none; } /* コピー成功で色とラベルが切り替わる */ .bnto-cp1.is-done { background: hsl(150 58% 42%); } .bnto-cp1.is-done .lb { display: none; } .bnto-cp1.is-done .ok { display: inline; }
// data-bnto-copy を自動検出して初期化(複数設置OK・二重実行OK) (function () { // navigator.clipboard(https必須)→ 非対応なら execCommand へ function bntoCopy(text, done) { if (navigator.clipboard && window.isSecureContext) { navigator.clipboard.writeText(text).then(done, legacy); } else { legacy(); } function legacy() { var ta = document.createElement('textarea'); ta.value = text; ta.setAttribute('readonly', ''); ta.style.cssText = 'position:fixed;top:-9999px;opacity:0;'; document.body.appendChild(ta); ta.select(); try { document.execCommand('copy'); } catch (e) {} document.body.removeChild(ta); done(); } } document.querySelectorAll('[data-bnto-copy]').forEach(function (btn) { if (btn.dataset.bntoInit) return; btn.dataset.bntoInit = '1'; btn.addEventListener('click', function () { bntoCopy(btn.getAttribute('data-copy') || '', function () { btn.classList.add('is-done'); clearTimeout(btn._t); btn._t = setTimeout(function () { btn.classList.remove('is-done'); }, 1600); }); }); }); })();
使い方のコツ
コピーする文字列は data-copy 属性を書き換えるだけです。navigator.clipboard は https(または localhost)でしか動かない点に注意——このJSは非対応環境で自動的に execCommand('copy') へフォールバックします。