简体   繁体   English

鼠标和触摸事件无法正常工作

[英]Mouse and Touch events not working as expected

I'm trying to add a mouse and touch down and move event. 我正在尝试添加鼠标并downmove事件。 In the events function, I want to get the clientX amount. 在事件功能中,我想获取clientX金额。 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 未捕获的TypeError:无法读取未定义的属性“ 0”

When: 什么时候:

  • The mouse hovers over the orange box. 鼠标悬停在橙色框上。
  • The mouse clicks on window . 鼠标单击window
  • I touch window . 我触摸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 ? 如何添加触摸和鼠标downmove事件,然后获取clientX I have to add both touch and move event, because on a touchscreen laptop, there's both capability's. 我必须同时添加触摸和移动事件,因为在触摸屏笔记本电脑上,两者兼具。 (I'm using Chrome.) (我正在使用Chrome。)

JSFiddle 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 && e.touches[0].clientX) || e.clientX

e.touches is undefined therefore you got the error. e.touches未定义,因此出现错误。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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