【JS】【Vue3】【React】获取鼠标位置的方法:JavaScript、Vue 3和React示例
在JavaScript、Vue 3和React中获取鼠标位置的方法如下:
JavaScript:
document.addEventListener('mousemove', (event) => {
const mouseX = event.clientX;
const mouseY = event.clientY;
console.log({ mouseX, mouseY });
});
Vue 3:
<template>
<div @mousemove="getMousePosition">
移动鼠标以获取位置
</div>
</template>
<script>
export default {
methods: {
getMousePosition(event) {
const mouseX = event.clientX;
const mouseY = event.clientY;
console.log({ mouseX, mouseY });
}
}
}
</script>
React:
import React, { useState } from 'react';
const MouseTracker = () => {
const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });
const handleMouseMove = (event) => {
setMousePosition({
x: event.clientX,
y: event.clientY
});
};
return (
<div onMouseMove={handleMouseMove}>
移动鼠标以获取位置 ({mousePosition.x}, {mousePosition.y})
</div>
);
};
export default MouseTracker;
以上代码片段展示了如何在不同的框架中获取鼠标位置,并在控制台中打印出来。
评论已关闭