网页中的可交互元素有很多触发事件,其中最为常用的就是点击事件了,其中PC上的点击事件使用鼠标触发事件,代表鼠标的点击,例如onmousedown事件;移动终端例如手机、平板等一般使用touch,代表触屏操作,例如ontouchstart事件。
两者存在一定对应关系,又有所区别,本文就是在给一个项目做移动端兼容时解决遇到的触发问题,然后整理出来的。
鼠标触发事件
onclick
这是最常使用的鼠标触发事件,在用户鼠标单击或者按下回车键时触发。这意味着不只鼠标,使用键盘也可以触发,易用性更高。
ondbclick
用户鼠标双击时触发。
onmousedown
用户鼠标按下任意按键时触发,可以通过Button参数判断是哪个鼠标按键触发的这个事件,如果使用右键触发,则需屏蔽右键菜单。
onmouseup
用户鼠标释放按键时触发。
onmouseenter
用户光标从元素外部移动到元素范围内时触发,事件不冒泡,并且光标移动到后代元素上时不会触发。
onmouseleave
用户光标从元素内部移动到元素范围外时触发,事件不冒泡,并且光标移动到后代元素上时不会触发。
onmousemove
用户光标在元素内部移动时重复地触发,频率较高,需防抖节流。
onmouseout
用户光标由当前元素移动到另一个元素时触发。另一个元素可以是任意外部元素或者后代元素。
onmouseover
用户光标从一个元素外部移动到另一个元素范围内时触发。
注意,除了onmouseenter和onmouseleave外,其他鼠标事件都会冒泡,如果取消鼠标事件冒泡可能会影响浏览器的默认行为,取消鼠标事件的默认行为可能影响其他触发事件,因为鼠标事件和其他时间有密不可分的关系。
另外,当同时存在onmousedown、onmouseup、onclick事件时,按这一排列顺序触发。
当在同一个元素上相继触发onmousedown、onmouseup事件后,onclick事件才能触发,因此如果onmousedown、onmouseup其中一个事件被取消,则click触发不会触发。
例如在浏览网页时,鼠标按下点击了一个链接没有松开,这时突然改了主意不想点开,则会把按住的鼠标拖动到空白位置松开,这其实就是没有执行onmouseup事件(因为松开鼠标时指针不在当前元素范围内),从而取消onclick事件。
触屏触发事件
ontouchstart
按下手指时触发。
ontouchend
松开手指时触发。
ontouchmove
按下手指并拖动时触发,频率较高,需要节流防抖。
ontouchcancel
当一些更高级别的事件发生时(如电话接入或者弹出信息)会取消当前的touch操作,例如在游戏时被电话打断等。
注意,当移动端同时存在鼠标事件和触屏事件时,手指抬起的时候(触发ontouchend后),系统会自动判断接收到事件的元素的内容是否被改变。
如果内容被改变,则接下来的事件都不触发;如果没有改变,则按照onmousedown、onmouseup、click的顺序继续触发(前面还有ontouchstart和ontouchend)。
另外,只有在触发一个触屏事件时,才会触发上一个事件的onmouseout事件。
因为私事拖更了,汪汪。
奴才做了主人,
是决不肯废去“老爷”称呼的,
他的摆架子,
恐怕比他的主人还十足,还可笑。
《二心集·上海文艺之一瞥》
——鲁迅
评论
583513 384683Great V I should certainly pronounce, impressed with your site. I had no trouble navigating through all the tabs and related information ended up being truly simple to do to access. I recently found what I hoped for before you know it in the least. 439625
940678 411490Yeah bookmaking this wasnt a bad decision excellent post! . 920877
43766 19195really good put up, i definitely adore this internet web site, maintain on it 294726
14416 141950I enjoy searching by way of and I conceive this internet site got some truly useful stuff on it! . 619199
660156 834471cleaning supplies really should have earth friendly organic ingredients so that they do not harm the environment 804002
131808 332084I was reading some of your content on this internet site and I conceive this internet website is actually informative ! Maintain on putting up. 959864
103352 849707This was an incredible post. Actually loved studying your web site post. Your data was extremely informative and valuable. I think you will proceed posting and updating regularly. Looking forward to your subsequent 1. 772480
597957 372959Its truly a cool and beneficial piece of data. Im glad which you shared this beneficial info with us. Please maintain us informed like this. Thanks for sharing. 665567
384611 381766 An interesting discussion is worth comment. I feel which you need to write more on this topic, it may well not be a taboo subject but generally folks are not enough to speak on such topics. Towards the next. Cheers 99753