鼠标滑动(5-1)

DOM

阻止冒泡与否

进入 onmouseover onmouseenter
手动阻止冒泡 默认阻止冒泡
移出 onmouseout onmouseleave
手动阻止冒泡 默认阻止冒泡


demo显示–图片10
鼠标跟随计算坐标图片9
描述:

  • [ ] 绘制一大box
  • [ ] 当鼠标移动到box上,create一个小盒子mark元素,并添加到box元素
  • [ ] 根据图9计算mark跟随的坐标,随鼠标移动
  • [ ] 当鼠标移出大box时,mark消失

(手动阻止冒泡)使用onmouseover/out

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
var box = document.getElementById("box");
box.onmouseover = function(e) {
e = e || window.event;
var mark = document.createElement("div");
mark.id = "mark";
this.appendChild(mark);
mark.style.left = e.clientX - this.offsetLeft + 5 + "px";
mark.style.top = e.clientY - this.offsetTop + 5 + "px";
//不阻止mark的onmouseover的冒泡会出现问题(重复创建mark):当鼠标移动过快时,鼠标会进入mark里,触发它的mouseover行为,由于时间冒泡机制,导致box的mouseover会重新被触发,导致红色盒子一直不断创建(只要进mouseover红盒子就会mouseover蓝盒子,就会重新创建红盒子)
mark.onmouseover = function(e) {
e = e || window.event;
e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;
}
//不阻止mark的onmouseout的冒泡会会先问题(闪--删一个创建一个):鼠标快速移动,首先进到mark上,此时浏览器在计算mark的位置,计算完成,mark到指定的位置,此时鼠标又重新回到box上,触发了mouseover也触发了mark的mouseout,mark的mouseout被触发,也会传播到box的mouseout,会把mark先删除
mark.onmouseout = function(e) {
e = e || window.event;
e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;
}
}
box.onmousemove = function(e) {
e = e || window.event;
var mark = document.getElementById("mark");
if (mark) {
mark.style.left = e.clientX - this.offsetLeft + 5 + "px";
mark.style.top = e.clientY - this.offsetTop + 5 + "px";
}
}
box.onmouseout = function(e) {
e = e || window.event;
var mark = document.getElementById("mark");
if (mark) {
this.removeChild(mark);
}
}

(默认阻止冒泡)使用onmouseenter/leave

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var box = document.getElementById("box");
box.onmouseenter = function(e) {
e = e || window.event;
var mark = document.createElement("div");
mark.id = "mark";
this.appendChild(mark);
mark.style.left = e.clientX - this.offsetLeft + 5 + "px";
mark.style.top = e.clientY - this.offsetTop + 5 + "px";
}
box.onmousemove = function(e) {
e = e || window.event;
var mark = document.getElementById("mark");
if (mark) {
mark.style.left = e.clientX - this.offsetLeft + 5 + "px";
mark.style.top = e.clientY - this.offsetTop + 5 + "px";
}
}
box.onmouseleave = function(e) {
e = e || window.event;
var mark = document.getElementById("mark");
if (mark) {
this.removeChild(mark);
}
}