JS: Touch equivalent for mouseenter

后端 未结 5 859
太阳男子
太阳男子 2021-02-04 01:55

is there a touch equivalent of the mouseenter.

I would like to detect if user slide on my DIV.

I prefer a solution depending directly on the target element not o

5条回答
  •  清酒与你
    2021-02-04 02:36

    2019: Yes-ish: Using pointerenter.

    By default, a touch causes a browser to 'capture' the pointer such that following events are scoped to that touched element. This prevents pointerleave/enter events, unless you explicitly release the capture. Also, I'm pretty sure you have to set touch-action:none on relevant elements to avoid the browser intercepting touches for default pan/zoom etc.

    Example:

    CSS:

    *{ touch-action: none; } 
    

    JS:

    let div = document.querySelector("div")
    div.addEventListener("pointerdown",(e)=>{
        console.log("down")
        console.log("attempt release implicit capture")
        div.releasePointerCapture(e.pointerId) // <- Important!
    })
    div.addEventListener("pointerenter",(e)=>{
        console.log("enter")
    })
    div.addEventListener("pointerleave",(e)=>{
        console.log("leave")
    })
    

    Works in Chrome at least. Not so much in Mobile Safari 13 beta though... According to the w3c specs, I'm fairly certain it should work this way. Maybe when iOS 13 is officially released we'll be in the clear. [I've filed a bug and looks like it's being attended to.]

    [Update: iOS 13 issue fixed. Should work in Chrome/FF/Safari]

提交回复
热议问题