触摸屏和 Javascript DOM Mousedown 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14887541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Touch Screen and Javascript DOM Mousedown Event
提问by crankshaft
I have a javascript web application that uses a touchscreen, browser is webkit based.
我有一个使用触摸屏的 javascript web 应用程序,浏览器是基于 webkit 的。
I am having a problem with this:
我遇到了这个问题:
addEventListener("mousedown", function(event){
console.log('down fired');
event.target.classList.add('down');
}, true);
When using a mouse, the target element class is added immediately when the mouse is held down, but when using the touchscreen, the target element class is not changed when the finger is held on the element.
当使用鼠标时,当鼠标被按住时,目标元素类会立即添加,但在使用触摸屏时,当手指放在元素上时,目标元素类不会改变。
The strange thing is however, the console log message is sent on the down event for both the mouse click and the ts press.
然而,奇怪的是,控制台日志消息是在鼠标单击和 ts 按下的 down 事件上发送的。
Any suggestions on how to solve this ??
有关如何解决此问题的任何建议?
Thanks
谢谢
EDIT
编辑
I added the touchstart event listener, but it does not fire on a touch event:
我添加了 touchstart 事件侦听器,但它不会触发触摸事件:
addEventListener("touchstart", function(event){
cl('touch fired');
}, true);
回答by Ro NL
Way too late, but maybe someone else could use it:
太晚了,但也许其他人可以使用它:
event.target
doesn't work on touchscreen, because you could use more than 1 finger, so there are more targets:
event.target
在触摸屏上不起作用,因为你可以使用 1 个以上的手指,所以有更多的目标:
addEventListener("mousedown", function(event){
console.log('down fired');
var t = /touch/.test(event.type) ? event.targetTouches[0] : event.target;
t.classList.add('down');
}, true);
回答by Code.Town
Use touchstart and touchend events instead.
请改用 touchstart 和 touchend 事件。
addEventListener("touchstart", function(event){
console.log('down fired');
event.target.classList.add('down');
}, true);
回答by Mark Ormston
Though generally a touch device does send the mouse events as expected, there are special events for touch screens. Specifically 'touchstart' as the equivalent of 'mousedown', and 'touchend'/'touchcancel' as the equivalents of 'mouseup'. If you are not checking what button or position is being touched, you can generally do a direct replacement with them.
虽然通常触摸设备确实按预期发送鼠标事件,但触摸屏也有特殊事件。特别是“touchstart”相当于“mousedown”,“touchend”/“touchcancel”相当于“mouseup”。如果您不检查正在触摸的按钮或位置,您通常可以直接替换它们。
By the way, touchend means the user stopped touching the screen. touchcancel occurs when something happens (like a non-browser alert) that intercepts the touch.
顺便说一下,touchend 意味着用户停止触摸屏幕。touchcancel 发生在发生拦截触摸的事情(如非浏览器警报)时。