英文:
React onMouseEnter event for getting X and Y axis of the element
问题
const handleonHover = () => {
// 获取来自 div 的 y 轴位置
const rect = event.target.getBoundingClientRect();
console.log("Y 轴位置", rect.y);
}
<div onMouseEnter={() => handleonHover()}>(高度:400px,宽度:300px)
<Image>
// 图片(高度:200px,宽度:100px)
</Image>
</div>
当鼠标进入 div 时,得到的 Y 轴位置为 400,但当鼠标悬停在 div 内部的图片上时,得到的 Y 轴位置与图片不同(Y 轴位置 - 430)。如何根据 div(父元素)的位置而不是图片(子元素)的位置来获取 Y 轴位置?
英文:
const handleonHover=()=>{
//get to know the y axis position from the div
const rect = event.target.getBoundingClientRect();
console.log("POS OF Y",rect.y)
}
<div onMouseEnter={()=>handleonHover()}>(height:400px,width:300px)
<Image>
//image (height:200px,width:100px)
</Image>
</div>
when mouse enter on the div got y axis (Y Axis - 400), but when
hover on the image that placed inside the div got the Y axis from the
image is different (Y Axis - 430). how to get the Y axis as per the
div (parent) position not image (Child) position?
答案1
得分: 0
The onMouseEnter event will return the actual hovered element inside the element you're listening to, or if there's nothing else there, it will return itself. If you want to bypass this issue, you have a short solution using the ref function.
const ref = useRef(null)
const onHover = (e) => {
var rect = ref.current.getBoundingClientRect()
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
console.log(x, y);
}
<div ref={ref} onMouseEnter={onHover}>
<img src="{your image}" alt="" />
</div>
Alternatively, you can simply add the CSS property "pointer-events: none;" to the elements inside the parent element. But it is less safe than the first solution.
Remember to import useRef first:
import { useRef } from 'react';
英文:
The onMouseEnter event will return the actual hovered element inside the element you're listening to, or if there's nothing else there, it will return itself. If you want to bypass this issue, you have a short solution using the ref function.
const ref = useRef(null)
const onHover = (e) => {
var rect = ref.current.getBoundingClientRect()
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
console.log(x,y);
}
<div ref={ref} onMouseEnter={onHover}>
<img src="{your image}" alt="" />
</div>
Alternatively, you can simply add the CSS property "pointer-events: none;"
to the elements inside the parent element.
But it is less safe than the first solution.
Remember to import useRef first
import { useRef } from 'react';
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论