javascript - 如何为“触摸”事件制作“鼠标离开”模拟?
问题描述
如果手指超出事件所附加的对象的边界,如何使touchMove 事件中断?并且在中断时,调用另一个函数。
我假设我需要以某种方式确定发生事件的对象的位置,并且在退出这些坐标时会以某种方式中断事件。但是我找不到如何在 React 中使用 useRef 以及如何中断事件。
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>
);
}
解决方案
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()
}
推荐阅读
- vba - 在多个 VBscript 之间共享变量(对象)
- oracle - 在 ORACLE INSERT 之后使用 Entity Framework Core 获取新 ID
- wso2 - 集群环境中的 WSO2 DS 计划任务
- javascript - 从 JavaScript 任务列表中删除动态生成的列表项
- spring - 为什么我不能在没有 SpringBootApplication 的情况下在 @SpringBootTest 中为库实例化 CrudRepository?
- python - Python List 对象没有属性位置
- python - Web Scraping - 在输入标签内写入
- matlab - 如何在 MATLAB 上绘制概率密度图
- r - 根据特定条件从另一个向量中的值替换向量中的值
- java - 从 ActionListener 调用时,JProgressbar 不显示