Dar*_*ava 6 javascript click touch
我知道您可以按照以下答案检测浏览器是否在带有触摸屏的设备上运行:/sf/answers/337392051/
但是,我知道有些设备同时具有触摸屏和鼠标。我可以检测出这些类型的触摸之间的差异吗?本质上我想区分 3 个不同的事件:(onClick在单击或触摸时触发),onTouch(仅在触摸时触发),onMouseClick(仅在单击时触发)。
Jac*_*cob 10
您可以使用pointerTypeon 属性PointerEvent来检测输入类型("mouse"、"touch"或"pen"):
element.addEventListener('pointerdown', (event) => {
if (event.pointerType === "mouse") {}
if (event.pointerType === "touch") {}
if (event.pointerType === "pen") {}
});
Run Code Online (Sandbox Code Playgroud)
如果您希望每种类型的点击都有特定事件,您可以创建自定义事件:
const mouse = new Event("mouseclick");
const touch = new Event("touch");
document.addEventListener("pointerdown", ({ pointerType, target }) => {
if (pointerType === "mouse") target.dispatchEvent(mouse);
if (pointerType === "touch") target.dispatchEvent(touch);
});
const someElement = document.querySelector(".box");
someElement.addEventListener("mouseclick", () => {
console.log("Clicked with mouse");
});
someElement.addEventListener("touch", () => {
console.log("Touched with mobile device");
});
someElement.addEventListener("click", () => {
console.log("Clicked by some device (we don't know)");
});Run Code Online (Sandbox Code Playgroud)
.box {
position: absolute;
inset: 2em;
background: darkred;
padding: 1em;
}Run Code Online (Sandbox Code Playgroud)
<div class="box">A box with custom events</div>Run Code Online (Sandbox Code Playgroud)
(注:未在触摸屏设备上进行测试)
请注意,如果您使用 React 或其他框架,则可能有不同的方法来创建自定义事件。
例如,在 React 中,您可以使用可重用函数来实现这些事件:
const clickEvents = ({ onMouseClick, onTouch, onClick }) => ({
onClick,
onPointerDown({ pointerType }) {
if (pointerType === "mouse") onMouseClick();
if (pointerType === "touch") onTouch();
},
});
function SomeComponent({ onClick, onMouseClick, onTouch, children }) {
const clickEventProps = clickEvents({ onClick, onMouseClick, onTouch });
return (
<div className="something" {...clickEventProps}>
<p>Custom events on this thing</p>
{children}
</div>
);
}
Run Code Online (Sandbox Code Playgroud)