Skip to content

Instantly share code, notes, and snippets.

@sharapeco
Last active June 19, 2018 01:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sharapeco/59336556ed5ed4f81a93feed004aac67 to your computer and use it in GitHub Desktop.
Save sharapeco/59336556ed5ed4f81a93feed004aac67 to your computer and use it in GitHub Desktop.
ブラウザに表示中の文字列をクリップボードにコピーする(jQueryを使用した実装)
/*
ブラウザに表示中の文字列をクリップボードにコピーする(jQueryを使用した実装)
jQuery + Bootstrap (v3) を使用している場合にすぐ動くコード。
次のようにマークアップすると、そのすぐあとにコピーするためのボタンが生成される。
<span class="js-cbcopy">コピーしたい文字列</span>
*/
$(function() {
function CBCopy(E) {
var me = this;
me.E = $(E);
me.btn = $("<button>").attr({type: "button", title: "URLをコピー"});
me.btn.append($("<span>").addClass("glyphicon glyphicon-duplicate"));
me.btn.on("click", function() { me.copy(); });
me.E.after(me.btn);
}
CBCopy.prototype = {
copy: function() {
var me = this, selection;
selection = document.getSelection();
selection.selectAllChildren(me.E[0]);
document.execCommand("copy");
selection.removeAllRanges();
}
};
$(".js-cbcopy").each(function() {
new CBCopy(this);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment