この前任意の文字列をQRコードで出力するのをGithub Pagesのお試し用に作ったんですが
現在のURLをQR出力するだけのスニペットもほしいかもと思い書いてみました。
というかボタン押してモーダルを出すところまではChatGPTに書かせました。
QR出すところだけ人力(つっても3行くらい)。
ライブラリはqrcodejsを使わせてもらってます。
https://github.com/davidshimjs/qrcodejs
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Modal Example</title> <style> /* スタイルを追加して、モーダルが中央に表示されるようにする */ dialog { width: 80%; max-width: 600px; padding: 20px; border: 1px solid #888; background-color: #fefefe; } /* ボタンを画面の右下に配置するスタイル */ #myBtn { position: fixed; bottom: 20px; right: 20px; padding: 10px 20px; font-size: 16px; background-color: #007bff; color: #fff; border: none; border-radius: 5px; cursor: pointer; } </style> </head> <body> <!-- モーダルを開くボタン --> <button id="myBtn">Open Modal</button> <!-- モーダル本体 --> <dialog id="myModal"> <button id="closeBtn">×</button> <div id="qr"></div> </dialog> <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script> <script> // ボタンを取得 var btn = document.getElementById("myBtn"); // モーダルを取得 var modal = document.getElementById("myModal"); // 閉じるボタンを取得 var closeBtn = document.getElementById("closeBtn"); // ボタンをクリックした時にモーダルを表示する btn.onclick = function() { modal.showModal(); } // 閉じるボタンをクリックした時にモーダルを非表示にする closeBtn.onclick = function() { modal.close(); } new QRCode(document.getElementById("qr"), window.location.href); </script> </body> </html>
既存のHTMLにモーダル出すscriptタグ埋め込むならこんな感じ。
コードは適当です。QRコードクリックで閉じるようになっています。
style当てるなり閉じるボタン作るなりはお好みでどうぞ。
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script> <script> var modal = document.createElement('dialog'); var qr_area = document.createElement('div'); qr_area.id="qr"; modal.appendChild(qr_area) document.body.appendChild(modal); new QRCode(document.getElementById("qr"),window.location.href); qr_area.onclick = function(){modal.close()} var btn = document.createElement('button'); btn.textContent = 'QRコード表示'; btn.style.position = 'fixed'; btn.style.bottom = '20px'; btn.style.fontSize = '16px'; btn.onclick = function(){modal.showModal()} document.body.appendChild(btn); </script>