mouseover
<!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>
<style>
.outer {
box-sizing: border-box;
margin: 50px auto;
padding-top: 20px;
width: 200px;
height: 200px;
background-color: #f40;
}
.inner {
margin: 0 auto;
width: 100px;
height: 100px;
background-color: lightgreen;
}
</style>
</head>
<body>
<div class="outer">
<div class="inner"></div>
</div>
<script>
let outer = document.getElementsByClassName('outer')[0],
inner = document.getElementsByClassName("inner")[0];
outer.onmouseover = function() {
console.log('outer onmouseover')
}
outer.onmouseout = function() {
console.log('outer onmouseout')
}
inner.onmouseover = function() {
console.log('inner onmouseover')
}
inner.onmouseout = function() {
console.log('inner onmouseout')
}
</script>
</body>
</html>
示例图如下
mouseenter(进入事件【推荐】)
<!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>
<style>
.outer {
box-sizing: border-box;
margin: 50px auto;
padding-top: 20px;
width: 200px;
height: 200px;
background-color: #f40;
}
.inner {
margin: 0 auto;
width: 100px;
height: 100px;
background-color: lightgreen;
}
</style>
</head>
<body>
<div class="outer">
<div class="inner"></div>
</div>
<script>
let outer = document.getElementsByClassName('outer')[0],
inner = document.getElementsByClassName("inner")[0];
outer.onmouseenter = function() {
console.log('outer onmouseenter')
}
outer.onmouseleave = function() {
console.log('outer onmouseleave')
}
inner.onmouseenter = function() {
console.log('inner onmouseenter')
}
inner.onmouseleave = function() {
console.log('inner onmouseleave')
}
</script>
</body>
</html>
示例图如下
补充:
- mouseenter 和 mouseleave默认阻止事件的冒泡机制
- 会受到元素层级关系的影响,满足生活上的理解
- 在项目开发中推荐使用它俩