<!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>
#pannel {
background-color: red;
width: 200px;
display: flex;
}
#left, #right {
flex: 1;
height: 100px;
}
#left {
background-color: blue;
}
#right {
background-color: green;
}
</style>
<script>
window.onload = function() {
const pannelEl = document.querySelector('#pannel')
pannelEl.onmouseover = function() {
console.log('mouse over')
}
pannelEl.onmouseout = function() {
console.log('mouse out')
}
}
</script>
</head>
<body>
<p>在left和right之间来回切换,会反复触发父容器的onmouseover和onmouseout事件</p>
<div id="pannel">
<div id="left">left</div>
<div id="right">right</div>
</div>
</body>
</html>
因为
mouseover
和mouseout
是会冒泡的,如果你想要更符合直觉的移入移出反馈,应该使用不会冒泡的mouseenter
和mouseleave
事件。