用途
新着
履歴
分類

JS マウスの位置の取得

JS マウスの位置の取得
マウスが要素の上に来た時の位置を取得するサンプルです。

マウスオーバーしたときと、クリックされたとき、それぞれのマウスの位置を取得します。

以下の正方形にマウスを合わせてください。

スマホではタップした時がトリガーになります。

マウスの位置

クリックされた位置

JSは以下



//ボタンの定義
const btn = document.getElementById('demo_btn');
//出力場所の定義
const output1 = document.getElementById('demo_area1');
const output2 = document.getElementById('demo_area2');

//ボタンエリアの座標を取得
btnRect = btn.getBoundingClientRect();

//マウスのホバー時に位置を取得
function get_move(event) {
    x = event.x - btnRect.left;
    y = event.y - btnRect.top;
    output1.innerHTML=`x : ${x} y : ${y}`;
}
btn.addEventListener('mousemove', get_move);


//マウスのクリック時に位置を取得
function get_click(event) {
    x = event.x - btnRect.left;
    y = event.y - btnRect.top;
    output2.innerHTML=`x : ${x} y : ${y}`;
}
btn.addEventListener('click', get_click);

CSS

#demo_btn{
    border: solid 1px #999;
    height: 120px;
    width: 120px;
    display: grid;
    grid-template-rows: repeat(3,40px);
    grid-template-columns: repeat(3,40px);
}

.demo_hover {
    border: 1px solid #000;
    box-sizing: border-box;
    user-select: none;
}
.demo_hover:hover {
    background: #00f;
}
.demo_hover:active {
    background: #f00;
}

#demo_area1,#demo_area2{
    height: 20px;
    line-height: 20px;
}

HTMLは以下になります


<div id="demo_btn">
    <div class="demo_hover"></div>
    <div class="demo_hover"></div>
    <div class="demo_hover"></div>
    <div class="demo_hover"></div>
    <div class="demo_hover"></div>
    <div class="demo_hover"></div>
    <div class="demo_hover"></div>
    <div class="demo_hover"></div>
    <div class="demo_hover"></div>
</div>

<p class=down >マウスの位置</p>

<div id="demo_area1"></div>

<p class=down >クリックされた位置</p>
<div id="demo_area2"></div>
公開 2022-04-01 08:46:11
更新 2022-04-07 08:07:06
このページの二次元コード
JS マウスの位置の取得

人気のサンプル

search -  category -  about
© 2024 kipure
Top