作るもの
左上に「html」「css」「javascript」の付箋が表示され、クリックするとソースコードをコピーするPRE要素を作る
コピペ用ソースコード
<pre class="note note-html"> </pre> <pre class="note note-css"> </pre> <pre class="note note-js"> </pre>
pre.note { position: relative; /* 要素の位置を相対指定する */ display: block; /* 要素をインラインブロックとして表示する */ padding: 30px 2em 2em; /* 要素内側の余白を指定する */ background-color: #f8f8f8; /* 背景色を指定する */ box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3); /* 影を付ける */ border-radius: 5px; /* 角丸を指定する */ font-family: Arial, sans-serif; /* フォントを指定する */ font-size: 14px; /* フォントサイズを指定する */ line-height: 1.5; /* 行の高さを指定する */ color: #333; /* 文字色を指定する */ } pre.note:before { position: absolute; /* 挿入されたテキストの位置を絶対指定する */ top: 0; /* 要素上部からの距離を指定する */ left: 0; /* 要素左部からの距離を指定する */ padding: 2px 7px; /* 要素内側の余白を指定する */ border-radius: 5px 0; /* 角丸を指定する */ font-family: Arial, sans-serif; /* フォントを指定する */ font-size: 12px; /* フォントサイズを指定する */ font-weight: bold; /* フォントの太さを指定する */ } pre.note.note-html:before { content: "html"; /* 要素の前にテキストを挿入する */ background-color: #2d95de; /* 背景色を指定する */ border: 1px solid #2d95de; /* ボーダーを指定する */ color: #fff; /* 文字色を指定する */ } pre.note.note-css:before { content: "css"; /* 要素の前にテキストを挿入する */ background-color: #de2d95; /* 背景色を指定する */ border: 1px solid #de2d95; /* ボーダーを指定する */ color: #fff; /* 文字色を指定する */ } pre.note.note-js:before { content: "javascript"; /* 要素の前にテキストを挿入する */ background-color: #95de2d; /* 背景色を指定する */ border: 1px solid #95de2d; /* ボーダーを指定する */ color: #333; /* 文字色を指定する */ } .popup { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: #333; color: white; padding: 20px; box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2); opacity: 0; pointer-events: none; transition: all 0.5s ease-out; } .popup.visible { opacity: 1; pointer-events: auto; transform: translate(-50%, -50%); } .popup.visible-out { opacity: 0; pointer-events: none; transform: translate(-50%, -60%); }
function preNodePopup() { // 「Copy code」ボタンをクリックしたときに、preタグの中身をクリップボードにコピーする var preElements = document.querySelectorAll('pre.note'); for (var i = 0; i < preElements.length; i++) { preElements[i].addEventListener('click', function (event) { var code = event.target.innerText; navigator.clipboard.writeText(code).then(function () { var popup = document.createElement('div'); popup.innerHTML = 'コードがクリップボードにコピーされました'; popup.classList.add('popup'); popup.classList.add('visible'); document.body.appendChild(popup); setTimeout(function () { popup.classList.remove('visible'); }, 1000); }, function () { }); }); } } // ロード時の処理 window.addEventListener('load', function() { preNodePopup(); });