以下示例是关于Html中包含鼠标跟踪器用法的示例代码,想了解鼠标跟踪器的具体用法?鼠标跟踪器怎么用?鼠标跟踪器使用的例子?那么可以参考以下相关源代码片段来学习它的具体使用方法。
<div class="mouse-stalker">
<div class="inner">
</div>
</div>
.mouse-stalker {
display: flex;
align-items: center;
justify-content: center;
width: 1px;
height: 1px;
position: fixed;
top: 0;
left: 0;
z-index: 1000;
pointer-events: none;
.inner {
width: 50px;
height: 50px;
border-radius: 50%;
background: #fff;
flex-shrink: 0;
}
}
// マウスストーカー要素
const mouseStalker = document.querySelector(".mouse-stalker");
// マウスストーカー要素の座標
const stalker = {
x: 0,
y: 0,
};
// マウスの座標
const mouse = {
x: 0,
y: 0,
};
// マウスストーカーの位置を更新
document.addEventListener("DOMContentLoaded", update);
// マウスの座標を監視
document.addEventListener("mousemove", mousemove);
// 変化したマウスの座標を格納
function mousemove(e) {
mouse.x = e.clientX;
mouse.y = e.clientY;
}
// 更新処理
function update() {
// マウスストーカー要素の座標を更新
/*
マウスストーカーの追従に余韻を持たせたい場合
stalker.x += (mouse.x - stalker.x) * 0.1;
stalker.y += (mouse.y - stalker.y) * 0.1;
上記のように希望の数値を掛ける
*/
stalker.x += mouse.x - stalker.x;
stalker.y += mouse.y - stalker.y;
// マウスストーカー要素の位置を小数点第一位まで四捨五入
const x = Math.round(stalker.x * 10) / 10;
const y = Math.round(stalker.y * 10) / 10;
// マウスストーカー要素のスタイルを更新
mouseStalker.style.transform = `translate3d(` + x + "px," + y + "px, 0)";
// update()内でupdateを呼び出す事でループさせる
requestAnimationFrame(update);
}
本文地址:https://www.itbaoku.cn/snippets/785421.html