在 JavaScript 中,鼠标事件是 Web 开发中最常用的事件类型,本篇算是笔记吧。
在DOM2.0中,W3C对鼠标事件作了现范,鼠标事件被解析为MouseEvent(我们可以用e.constructor == MouseEvent来判断其是否为鼠标事件。
常见的鼠标事件有
click、dblclick 没有什么好讲的,contextmenu用的也不多讲。重点讲下mouse事件。
focus跟blur不是鼠标事件,但是也是由鼠标触发。focus跟blur的 e.constructor 为FocusEvent
Mouse事件有7种,分别是:
当二者都没有子元素时,二者的行为是一致的,但是二者内部都包含子元素时,行为就不同了.
总结就是:
mouseover和mouseenter的异同体现在两个方面:
可见mouseover事件因其具有冒泡的性质,在子元素内移动的时候,频繁被触发,如果我们不希望如此,可以使用mouseenter事件代替之,但是早期只有ie浏览器支持该事件。
结合其对称事件, mouseleave, mouseenter DOM事件的行为方式与CSS :hover 伪类非常相似。
还有就是:mouseover先触发,mouseenter 后触发。离开时,却是 mouseout 先触发,mouseleave后触发
下来看下面代码
<html>
<head>
<title>dsafsa</title>
</head>
<body>
<input id="test" style="width: 100px;height: 100px;border: 1px solid #ccc;"></input>
<script>
let test = document.getElementById('test')
test.addEventListener('mousedown',()=>console.log('mousedown'))
test.addEventListener('mouseover',()=>console.log('mouseover'))
test.addEventListener('mouseenter',()=>console.log('mouseenter'))
test.addEventListener('mouseup',()=>console.log('mouseup'))
test.addEventListener('focus',()=>console.log('focus'))
test.addEventListener('blur',()=>console.log('blur'))
test.addEventListener('mousemove',()=>console.log('mousemove'))
test.addEventListener('mouseleave',()=>console.log('mouseleave'))
test.addEventListener('mouseout',()=>console.log('mouseout'))
test.addEventListener('click',()=>console.log('click'))
test.addEventListener('touchstart',()=>console.log('touchstart'))
test.addEventListener('touchmove',()=>console.log('touchmove'))
test.addEventListener('touchend',()=>console.log('touchend'))
</script>
</body>
</html>
看看结果如何
打印顺序为:
mouseover-》mouseenter-》mousemove-》-》mousedown-》focus-》-》mouseup-》click-》mousemove-》mouseout-》mouseleave-》blur
tochstart -》touchend-》click
这个是普通html元素。但是如果是input呢?
需要注意的是:移动端,普通元素是不会触发 focus 与blur的,只有表单元素才会触发,如input输入框
执行顺序是 tochstart -》touchend-》-》mousedown-》focus-》mouseup-》click-》blur
mousedown左右键按操按下均可触发,那么怎么区分左右键呢?
是左键点击还是右键点击由它的一个叫button的属性判定。以下就是W3C的标准现范:
当然微软是不会妥协的,因为e.button本来就是微软最先实现的,网景用的是e.which,但相对而言,微软的复杂多了。
参考文章:
JS鼠标事件(非常详细) http://c.biancheng.net/view/5944.html
mouseover和mouseenter的区别 https://www.cnblogs.com/psxiao/p/11543333.html
javascript 鼠标事件总结 https://www.cnblogs.com/rubylouvre/archive/2009/08/24/1552862.html
转载本站文章《JavaScript鼠标事件细讲:执行顺序+注意事项+区别比对》, 请注明出处:https://www.zhoulujun.cn/html/webfront/ECMAScript/js/2016_010
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。