Forked from vzvu3k6k/qiita-select-code-block.user.js
Last active
November 9, 2015 06:14
-
-
Save mystelynx/8a39eb098b5d0f9658b8 to your computer and use it in GitHub Desktop.
Qiitaの記事内のコード部分を楽にコピペする ref: http://qiita.com/vzvu3k6k/items/0a0abb0e848ed2c10651
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name Qiita: Select code block | |
// @description コードの右上のアイコンをクリックすると選択される | |
// @version 1.1 | |
// @match http://qiita.com/* | |
// @match https://*.qiita.com/* | |
// @namespace http://qiita.com/uraura/ | |
// @license Public Domain | |
// ==/UserScript== | |
var style = document.createElement("style"); | |
style.textContent = | |
'.code-frame .__select-code {' + | |
' display: none;' + | |
'}' + | |
'.code-frame:hover .__select-code {' + | |
' display: block;' + | |
' background: none repeat scroll 0 0 #EEEEEE;' + | |
' border-bottom: 1px solid #CCCCCC;' + | |
' border-left: 1px solid #CCCCCC;' + | |
' border-radius: 0 3px 0 3px;' + | |
' cursor: pointer;' + | |
' padding: 3px;' + | |
' float: right;' + | |
'}'; | |
document.head.appendChild(style); | |
document.addEventListener("DOMNodeInserted", function(e){ | |
var node = e.target; | |
if(node.nodeType == Node.ELEMENT_NODE && node.classList.contains("code-frame")) | |
if(!node.querySelector(".__select-code")) | |
addSelectButton(e.target); | |
}); | |
Array.prototype.forEach.call(document.querySelectorAll(".code-frame"), addSelectButton); | |
function addSelectButton(elmCodeFrame){ | |
var elmSelectButton = document.createElement("div"); | |
var icon = document.createElement("i"); | |
icon.className = 'fa fa-clipboard'; | |
elmSelectButton.appendChild(icon); | |
elmSelectButton.setAttribute("class", "__select-code"); | |
elmSelectButton.addEventListener("click", function(){ | |
select(elmCodeFrame.querySelector("pre")); | |
copyToClipboard(); | |
}); | |
elmSelectButton.insertAdjacentHTML("afterbegin", '<i class="icon-paper-clip"/>'); | |
elmCodeFrame.insertBefore(elmSelectButton, elmCodeFrame.firstChild); | |
} | |
function select(elm){ | |
var select = window.getSelection(); | |
select.removeAllRanges(); | |
var range = document.createRange(); | |
range.selectNodeContents(elm); | |
select.addRange(range); | |
} | |
function copyToClipboard() { | |
if (!document.queryCommandSupported('copy')) { | |
alert('copyに対応していません') | |
return | |
} | |
try { | |
document.execCommand('copy') | |
} catch (e) { | |
alert('copyに失敗しました') | |
} | |
} |
Author
mystelynx
commented
Nov 9, 2015
- Qiita:Teamに対応させた
- クリップボードへのコピー処理を入れた
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment