如果我们要用canvas做一个自己的画板,既能在pc上画又能在手机上画,这时候我们就要监听此时是鼠标事件还是触摸事件。
我们打开chrome开发者工具的控制台,
输入以下代码document.body.ontouchstart
我们会看到控制台输出undefined
我们调成模拟手机模式,
再输入上面的代码,可以看到输出的是null.
我们就可以设置如下代码判断当前是否为touch事件,进而执行触摸代码。
if(document.body.ontouchstart!==undefined){
//执行touch代码
}
else{
// 执行mouse代码
}
触摸事件有ontouchstart,ontouchmove,ontouchend
等,鼠标事件有onmousedown,onmousemove,onmouseup
等,具体可见MDN文档