javascript onmouseupでマウスからボタンが離れたイベントを取得する
- 作成日 2020.12.25
- 更新日 2022.07.29
- javascript
- javascript
javascriptで、onmouseupを使用してマウスからボタンが離れたイベントを取得するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 103.0.5060.134
onmouseup使い方
onmouseupを使用すると、マウスからボタンが離れたイベントを取得することが可能です。
※ホイールボタンのクリックにも反応します。
/* html内で利用 */
<タグ onmouseup ="イベント">
/* js内で利用 */
object.onmouseup = function(){ イベント };
onmouseup使い方(html内での使用例)
<div id="main" onmouseup="hoge()" style="padding: 10px; margin-bottom: 10px; border: 1px dashed #333333;">
<p>hello javascript!!</p>
</div>
<script>
'use strict';
function hoge(){
console.log('マウスから離れました');
};
</script>
onmouseup使い方(js内での使用例)
<div id="main" style="padding: 10px; margin-bottom: 10px; border: 1px dashed #333333;">
<p>hello javascript!!</p>
</div>
<script>
'use strict';
document.getElementById('main').onmouseup = function(){
console.log('マウスから離れました');
};
</script>
実行結果は、クリックしてマウスから離れた回数だけコンソールに「マウスから離れました」が表示されます。
macのsafari(13.1.1)でも同じです。
また、以下のコードを、
document.getElementById('main').onmouseup = function(){
console.log('マウスから離れました');
};
document.getElementByIdの省略と関数をアロー化して、簡潔に記述することもできます。
main.onmouseup = () => {
console.log('マウスから離れました');
};
addEventListener
addEventListenerに登録しても、同じ結果となります。
<div id="main" style="padding: 10px; margin-bottom: 10px; border: 1px dashed #333333;">
<p>hello javascript!!</p>
</div>
<script>
document.getElementById("main").addEventListener (
"mouseup", function(){ console.log('マウスから離れました')}
)
</script>
イベントの順番
ボタンが押されたイベントである「mousedown」と、ボタンが離れたイベントである「mouseup」と、クリックイベントである「click」は、「mousedown」→「mouseup」→「click」の順番で実行されます。
<div id="main" style="padding: 10px; margin-bottom: 10px; border: 1px dashed #333333;">
<p>hello javascript!!</p>
</div>
<script>
// ボタンが押されたイベント
document.getElementById("main").addEventListener (
"mousedown", function(){ console.log('mousedown')}
)
// ボタンが離れたイベント
document.getElementById("main").addEventListener (
"mouseup", function(){ console.log('mouseup')}
)
// クリック
document.getElementById("main").addEventListener (
"click", function(){ console.log('click')}
)
</script>
実行結果
サンプルコード
以下は、
マウスを要素内でクリックした後に離すと、カウントしてカウントした数を表示する
サンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
<!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 = () => {
main.onmouseup = () => { hoge() };
}
</script>
<body>
<div id="main" class="container mx-auto my-56 w-56 px-4">
<div class="flex justify-center">
<a id="result" class="bg-green-500 text-white py-2 px-8 rounded-full mb-3 mt-4">カウント</a>
</div>
</div>
</body>
</html>
カウントされていることが確認できます。
-
前の記事
php 配列の各値にコールバック関数を適用した結果を返す 2020.12.25
-
次の記事
python ファイルの読み込み処理を行う 2020.12.25
コメントを書く