如何为“触摸”事件制作“鼠标离开”模拟?

时间:2021-06-11 13:43:18

标签: javascript reactjs

如果手指超出了事件所附加的对象的边界,如何使touchMove事件被中断?并且在中断时调用另一个函数。

我假设我需要以某种方式确定发生事件的对象的位置,并在退出这些坐标时以某种方式中断事件。但是我找不到如何使用 useRef 在 React 中执行此操作以及如何中断事件。

const Scrollable = (props) => {
  const items = props.items;

  let ref = useRef();

  const touchStarts = (e) => {...}
  const touchEnd = (e) => {...}

  
  const touchMove = (e) => {
        if (ref && ref.current && !ref.current.contains(e.target)) {
        return;
      }
      e.preventDefault();
      ...
  }
  
  useEffect(() => {
    document.addEventListener("touchmove", touchMove);
    ...
    return () => {
      document.removeEventListener("touchmove", touchMove);
      ...
    };
  });

  return (
       <div>
          <div
          ref={ref}

          onTouchStart={touchStarts}
          onTouchMove={touchMove}
          onTouchEnd={touchEnd}
        >
        </div>
      </div>
    );
}

1 个答案:

答案 0 :(得分:0)

const touchMove =(e) => {
//Inside the touch event, we use the ref hook to take the coordinates of the object.
let posa = ref.current.getBoundingClientRect();

//Next, we check the coordinates of the touch using clientX / Y checking that the touch is inside the object.
if(e.touches[0].clientX > posa.left && 
   e.touches[0].clientX < posa.right && 
   e.touches[0].clientY > posa.top && 
   e.touches[0].clientY < posa.bottom ) { 
      ourFunc()
   } 
   //If the condition is not met, we call the function that should be triggered when the finger is released.
   else {
      stopFunc()
   }