javascript onpasteで貼り付けイベントを取得する
- 2021.01.17
- javascript
- javascript

javascriptで、onpasteを使用して、貼り付けイベントを取得するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 84.0.4147.105
onpaste使い方
onpasteを使用すると、貼り付けイベントを取得することが可能です。
1 2 3 4 5 |
/* html内で利用 */ <タグ onpaste ="イベント"> /* js内で利用 */ object.onpaste = function(){ イベント }; |
onpaste使い方(html内での使用例)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
/* html */ <div onpaste="hoge()" style="width: 200px; padding: 20px; margin-bottom: 10px; border: 1px dashed #333333;"> <p>Hello javascript</p> </div> /* javascript */ 'use strict'; function hoge(){ console.log('貼り付けが発生しました'); } |
onpaste使い方(js内での使用例)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
/* html */ <div id="main" style="width: 200px; padding: 20px; margin-bottom: 10px; border: 1px dashed #333333;"> <p>Hello javascript</p> </div> /* javascript */ 'use strict'; document.getElementById('main').onpaste = function(){ console.log('貼り付けが発生しました'); }; |
実行結果は、「貼り付け」を実行するたびに「貼り付けが発生しました」と表示されます。

macのsafari(13.1.1)でも、同じ結果となります。

また、以下のコードを、
1 2 3 |
document.getElementById('main').onpaste = function(){ console.log('貼り付けが発生しました'); }; |
document.getElementByIdと関数をアロー化して、簡潔に記述することもできます。
1 2 3 |
main.onpaste = () => { console.log('貼り付けが発生しました'); }; |
サンプルコード
以下は、
フォームにペーストイベントが発生するたびにカウントして、カウントした数を表示する
サンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>mebeeサンプル</title> <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"> </head> <script> let count = 0; const hoge = () => { count++; result.innerHTML = `貼り付けが実行された回数${count}`; } window.onload = () => { sample.onpaste = () => { hoge(); }; } </script> <body> <div id="main" class="container mx-auto my-56 w-56 px-4"> <div class="flex flex-col justify-center"> <p id="result" class="bg-blue-800 text-white py-2 px-4 rounded-full mb-3 mt-4">カウント</p> <input id="sample" type="text" class="shadow appearance-none border border-blue-500 rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline"> </div> </div> </body> </html> |
カウントされていることが確認できます。

-
前の記事
go言語 文字列に使用されている文字数を取得する 2021.01.16
-
次の記事
React.js UI「sonwan-ui」を使用する 2021.01.17
コメントを書く