在 JavaScript 中检测点击与触摸

Detect click vs. touch in JavaScript

我知道您可以检测浏览器是否 运行 在带有触摸屏的设备上按照这个答案:

但是,我知道有些设备既有触摸屏又有鼠标。我可以检测出这些类型的触摸之间的区别吗?基本上我想区分 3 个不同的事件:onClick(点击或触摸时触发),onTouch(仅在触摸时触发),onMouseClick(仅在点击时触发) .

您可以使用pointerType property on PointerEvent检测输入类型("mouse""touch""pen"):

element.addEventListener('pointerdown', (event) => {
  if (event.pointerType === "mouse") {}
  if (event.pointerType === "touch") {}
  if (event.pointerType === "pen") {}
});

如果您希望每种类型的点击都有特定的事件,您可以create custom events:

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>

(注意:未在触摸屏设备上测试)

请注意,如果您使用的是 React 或其他框架,则可能有不同的方法来创建自定义事件。

例如,在 React 中,您可以使用自定义挂钩实现这些事件:

const useClickEvents = ({ onMouseClick, onTouch, onClick }) => ({
  onClick,
  onPointerDown({ pointerType }) {
    if (pointerType === "mouse") onMouseClick(); 
    if (pointerType === "touch") onTouch(); 
  },
});
function SomeComponent({ onClick, onMouseClick, onTouch, children }) {
  const clickEventProps = useClickEvents({ onClick, onMouseClick, onTouch });
  return (
    <div className="something" {...clickEventProps}>
      <p>Custom events on this thing</p>
      {children}
    </div>
  );
}