写了段代码可以用来识别用户的操作方式是否为触摸。
首先需要给元素加一个便于批量添加事件的on方法(我自认为这么写没什么毛病
(function(){
function Extent_On_Event(){
if(arguments[0] instanceof Array){
var arg=arguments,es=arguments[0];
es.forEach(function(e){
arg[0]=e;
this.addEventListener.apply(this,arg);
});
}else{
this.addEventListener.apply(this,arguments);
}
return this;
};
(window.EventTarget||window.Node).prototype.on=Extent_On_Event;
if(!window.on)Window.prototype.on=Extent_On_Event;
})();
然后定义判断触摸模式的代码
//touchMode
(function(){
var isTouchMode=window.touchMode=('ontouchstart' in window);
var mouseEventRec=0;
function touchModeEvent(node){
node.on(['touchstart','touchend','touchmove'],function(){
mouseEventRec&&(mouseEventRec=0);
if(isTouchMode)return;
isTouchMode=window.touchMode=true;
var e=new Event('touchModeChange');
e.touchMode=isTouchMode;
window.dispatchEvent(e);
});
node.on('mousemove',function(){
if(!isTouchMode)return;
mouseEventRec++;
if(mouseEventRec>4){
isTouchMode=window.touchMode=false;
var e=new Event('touchModeChange');
e.touchMode=isTouchMode;
window.dispatchEvent(e);
};
});
}
touchModeEvent(window);
})();
这段代码的作用
- 在`window` 对象上定义touchMode变量,值为boolean,为true时是触摸模式,为false时是非触摸模式(大概就是鼠标模式)。如果你不希望出现此变量,删除相关赋值代码即可。
- 模式变动时在`window` 对象上触发`touchModeChange` 事件,event对象的touchMode属性为变动后的值。
在支持触摸的设备上,touchMode默认为true,移动鼠标后会转变为false。我认为这个地方是有点毛病的,但是不知道如何正确判断初始状态。
对于阻止以上代码中事件冒泡到window的元素,需要额外执行相关的监听代码以保证正确性。