简体   繁体   中英

Mouse and Touch events not working as expected

I'm trying to add a mouse and touch down and move event. In the events function, I want to get the clientX amount. I did the following to get it:

console.log(e.touches[0].clientX || e.clientX);

But I get the following error:

Uncaught TypeError: Cannot read property '0' of undefined

When:

  • The mouse hovers over the orange box.
  • The mouse clicks on window .
  • I touch window . (I also get the correct output though. So it seems like it's the function fires twice.)

How can I add a touch and mouse down and move event, then get clientX ? I have to add both touch and move event, because on a touchscreen laptop, there's both capability's. (I'm using Chrome.)

JSFiddle

 var myDiv = document.getElementById('myDiv'); window.addEventListener('mousedown', mouseDownFunction); window.addEventListener('touchstart', mouseDownFunction); myDiv.addEventListener('mousemove', mouseMoveFunction); myDiv.addEventListener('touchmove', mouseMoveFunction); function mouseDownFunction(e) { console.log(e.touches[0].clientX || e.clientX); } function mouseMoveFunction(e) { myDiv.innerHTML = e.touches[0].clientX || e.clientX; } 
 #myDiv { width: 100px; height: 100px; background-color: orange; } 
 <div id="myDiv"></div> 

Here you go :

Make expression as (e.touches && e.touches[0].clientX) || e.clientX (e.touches && e.touches[0].clientX) || e.clientX

e.touches is undefined therefore you got the error.

 var myDiv = document.getElementById('myDiv'); window.addEventListener('mousedown', mouseDownFunction); window.addEventListener('touchstart', mouseDownFunction); myDiv.addEventListener('mousemove', mouseMoveFunction); myDiv.addEventListener('touchmove', mouseMoveFunction); function mouseDownFunction(e) { console.log((e.touches && e.touches[0].clientX) || e.clientX); } function mouseMoveFunction(e) { myDiv.innerHTML = (e.touches && e.touches[0].clientX) || e.clientX; } 
 #myDiv { width: 100px; height: 100px; background-color: orange; } 
 <div id="myDiv"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM