React onMouseEnter事件,用于获取元素的X和Y轴坐标。

huangapple go评论60阅读模式
英文:

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=()=&gt;{
 //get to know the y axis position from the div 
 const rect = event.target.getBoundingClientRect();
 console.log(&quot;POS OF Y&quot;,rect.y)

}

&lt;div onMouseEnter={()=&gt;handleonHover()}&gt;(height:400px,width:300px) 
&lt;Image&gt;
//image (height:200px,width:100px) 
&lt;/Image&gt;
&lt;/div&gt;

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) =&gt; {
    var rect = ref.current.getBoundingClientRect()
    var x = e.clientX - rect.left; 
    var y = e.clientY - rect.top;  
    console.log(x,y);
  }

    &lt;div ref={ref} onMouseEnter={onHover}&gt;
        &lt;img src=&quot;{your image}&quot; alt=&quot;&quot; /&gt;
    &lt;/div&gt;

Alternatively, you can simply add the CSS property &quot;pointer-events: none;&quot; to the elements inside the parent element.
But it is less safe than the first solution.

Remember to import useRef first

import { useRef } from &#39;react&#39;;

huangapple
  • 本文由 发表于 2023年5月17日 22:11:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76273056.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定