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增加!!!
