在工作中,常常会分不清mouseente和mouseover,mouseleave和mouseout的区别,这里我们特别说明如下:
- mouseente是鼠标移入事件,与mouseover的区别是:mouseente鼠标从父元素移入到子元素上时不触发
- mouseleave是鼠标离开事件,与mouseout的区别是:mouseleave鼠标从子元素移出到父元素上时不触发
- 将mouseente和mouseleave绑定到父元素上时,仅当鼠标移入或移除父元素时触发。
复制代码
请看以下代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="d" style="width:200px;height:200px;border:1px solid red">
父元素
<div id="inner" style="width:100px;height:100px;border:1px solid gray">
子元素
</div>
</div>
<script type="text/javascript">
var d = document.getElementById('d');//获取父元素
// mouseenter和mouseleave不区分子元素(鼠标从父元素移动到子元素时不触发)
d.onmouseenter = function(){
console.log('enter');
}
d.onmouseleave = function(){
console.log('leave');
}
</script>
</body>
</html>
以上我们给父元素绑定了mouseente和mouseleave事件,当鼠标移入父元素时mouseente会触发,当鼠标移出父元素时mouseleave会触发,当鼠标在父元素和子元素之间移动时不触发,大家可以测试一下。
|