mouseover/mouseout
:::info
鼠标滑入滑出事件
一般在DOM
结构比较简单的时候使用
:::
<!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>
.box {
width: 200px;
height: 200px;
background-color: orange;
}
.box1 {
width: 100px;
height: 100px;
background-color: black;
}
</style>
</head>
<body>
<div class="box">
<div class="box1"></div>
</div>
</body>
</html>
<script>
// ...
</script>
这两个事件还存在事件冒泡:
var oBox = document.getElementsByClassName("box")[0];
var oBox1 = document.getElementsByClassName("box1")[0];
oBox.onmouseover = function () {
this.style.backgroundColor = "green";
};
oBox.onmouseout = function () {
this.style.backgroundColor = "orange";
};
oBox1.onmouseover = function (event) {
this.style.backgroundColor = "white";
};
oBox1.onmouseout = function () {
this.style.backgroundColor = "black";
};
这样很明显的看到,当我们把鼠标滑入进box1
后,box
的样式也被更改了!
另外该事件对元素本身和元素内部的子元素都会生效(有点像事件捕获的机制),
或者说当在元素的子元素上滑入滑出时也会触发父元素的滑入滑出事件!!!
var oBox = document.getElementsByClassName("box")[0];
var oBox1 = document.getElementsByClassName("box1")[0];
var overCount = 0,
outCount = 0;
oBox.onmouseover = function () {
overCount++;
console.log("onmouseover", overCount);
};
oBox.onmouseout = function () {
outCount++;
console.log("onmouseout", outCount);
};
可以看到当我们在元素内部滑入滑出姿元素的时候,box
的事件也会被触发!
mouseenter/mouseleave
:::info
鼠标滑入滑出事件
一般在DOM
结构复杂的时候使用
:::
该事件不存在「冒泡行为」。
但是有些情况下会被误以为是冒泡行为。
var oBox = document.getElementsByClassName("box")[0];
var oBox1 = document.getElementsByClassName("box1")[0];
oBox.onmouseenter = function () {
this.style.backgroundColor = "green";
};
oBox.onmouseleave = function () {
this.style.backgroundColor = "orange";
};
oBox1.onmouseenter = function (event) {
this.style.backgroundColor = "white";
};
oBox1.onmouseleave = function () {
this.style.backgroundColor = "black";
};
这样乍一看和mouseover/mouseout
的行为是一样的,但是当我们进行阻止冒泡操作的时候是无效的!!!
var oBox = document.getElementsByClassName("box")[0];
var oBox1 = document.getElementsByClassName("box1")[0];
oBox.onmouseenter = function () {
this.style.backgroundColor = "green";
};
oBox.onmouseleave = function () {
this.style.backgroundColor = "orange";
};
oBox1.onmouseenter = function (event) {
var event = event || window.event;
event.stopPropagation(); // 取消冒泡行为,但是无效!!!
this.style.backgroundColor = "white";
};
oBox1.onmouseleave = function () {
this.style.backgroundColor = "black";
};
这是因为mouseenter/mouserleave
只会对自己绑定的元素负责(因为box1
是box
的子元素,还是相当于在box
上滑入滑出)。
var oBox = document.getElementsByClassName("box")[0];
var oBox1 = document.getElementsByClassName("box1")[0];
var enterCount = 0,
leaveCount = 0;
oBox.onmouseenter = function () {
overCount++;
console.log("onmouseenter", overCount);
};
oBox.onmouseleave = function () {
outCount++;
console.log("onmouseleave", outCount);
};
当我们在box1
滑入滑出的时候,不会触发box
的滑入滑出事件去触发count
增加!!!