Flashを用いずJavaScriptでコピー&カット機能を実装する方法
2024/01/13
以前メモったようなFlashを用いる方法ではなく、WebAPIでコピー&カット機能を実装できるらしい。以下に以前の記事とサンプルとソースをメモ。
以前の記事
https://taitan916.info/blog/?p=419
サンプル
https://taitan916.info/sample/cut_copy/
ソース
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>document.execCommandでカット&コピー</title>
</head>
<body>
<textarea class="sample-text">サンプルテキスト</textarea>
<button class="cut btn">カット</button>
<button class="copy btn">コピー</button>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function(){
$('.btn').click(function(){
var key = ( $(this).hasClass('cut') ) ? 'cut' : 'copy';
var text = document.querySelector('.sample-text');
text.select();
try{
var successful = document.execCommand(key);
var msg = successful ? 'success!' : 'error!';
alert( msg );
}catch( err ){
console.log( err );
}
});
});
</script>
</body>
</html>
その他
利用可能ブラウザはchrome42,firefox41,IE9,Opera29となっており、safariやスマホ端末は無理っぽい。詳細は以下の通り。
https://developer.mozilla.org/ja/docs/Web/API/Document/execCommand#Browser_Compatibility
PCでの利用が前提のページでブラウザもある程度指定可能な、社内向けの管理画面とかで用いるのがよさそう。
関連記事
-
-
Ajaxでプラグイン無しのファイルアップロード方法
画像ファイルを添付できて、尚且つAjaxを用いた非同期通信のフォームを作りたかっ ...
-
-
formでdisplay:none;にしてても送信される
formで特定の部分をdisplay:none;で非表示にしてても 内容は送信さ ...
-
-
Ajaxで負荷軽減
業務中、専用のページでfile_get_contents的なものは あまり使わな ...
-
-
jQuery UIでカレンダーピッカー(Datepicker)の利用方法
フォーム等で日付を入力する際にカレンダーピッカー機能を実装することがある。その際 ...
-
-
jQueryでshow/hideよりaddClass/removeClassの方が速い
diaplay:none/blockする際に最近はshow()/hide()を ...