我知道你可以检测浏览器是否在触摸屏设备上运行,就像这个答案所示:https://dev59.com/y2445IYBdhLWcg3wg6tm#4819886
但是,我知道有些设备既有触摸屏也有鼠标。我能否区分这些类型的触摸?本质上,我想区分3种不同的事件:onClick
(点击或触摸时触发),onTouch
(仅在触摸时触发),onMouseClick
(仅在点击时触发)。
我知道你可以检测浏览器是否在触摸屏设备上运行,就像这个答案所示:https://dev59.com/y2445IYBdhLWcg3wg6tm#4819886
但是,我知道有些设备既有触摸屏也有鼠标。我能否区分这些类型的触摸?本质上,我想区分3种不同的事件:onClick
(点击或触摸时触发),onTouch
(仅在触摸时触发),onMouseClick
(仅在点击时触发)。
PointerEvent
的 pointerType
属性 来检测输入类型("mouse"
、"touch"
或 "pen"
):element.addEventListener('pointerdown', (event) => {
if (event.pointerType === "mouse") {}
if (event.pointerType === "touch") {}
if (event.pointerType === "pen") {}
});
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)");
});
.box {
position: absolute;
inset: 2em;
background: darkred;
padding: 1em;
}
<div class="box">A box with custom events</div>
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>
);
}
click
和dblclick
事件有类似的东西吗? - Lampe2020
pointerType
。 - Randy Casburn