一、事件类型
1、onclick : 单击;
2、ondblclick : 双击;
3、oncontextmenu : 右键菜单;
4、onmouseover , onmouseenter: 移入;
5、onmouseout , onmouseleave : 移出;
6、onmousedown : 按下;
7、onmouseup : 抬起;
8、onmousemove : 移动;
二、坐标位置
1、screenX 在屏幕中的x坐标,screenY 在屏幕中的y坐标;
2、相对于body:
●clientX 表示事件发生时鼠标指针在视口中的水平坐标(不包含滚动距离);
●clientY 在视口中的垂直坐标;
●IE没有的属性:pageX 在页面中的x坐标,pageY在页面中的y坐标;
3、获取点击目标的坐标(有兼容性):offsetX,offsetY;
三、建议使用onmouseenter和 onmouseleave,因为 onmouseover和 onmouseout在进入移出子级标签时触发。
四、鼠标事件案例——放大镜效果
<!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>放大镜</title>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
.shop {
float: left;
width: 300px;
height: 300px;
border: 1px solid gray;
background-image: url(https://img0.baidu.com/it/u=4162369564,2713428954&fm=253&fmt=auto&app=138&f=PNG?w=281&h=500);
background-size: 100% 100%;
position: relative;
margin-left: 200px;
}
.slider {
position: absolute;
width: 150px;
height: 150px;
background-color: cyan;
opacity: .5;
display: none;
}
.mirror {
width: 400px;
height: 400px;
border: 1px solid gray;
float: left;
overflow: hidden;
position: relative;
display: none;
}
.mirror img {
width: 800px;
height: 800px;
position: absolute;
}
</style>
</head>
<body>
<div class="shop">
<div class="slider"></div>
</div>
<div class="mirror">
<img src="https://img0.baidu.com/it/u=4162369564,2713428954&fm=253&fmt=auto&app=138&f=PNG?w=281&h=500" alt="">
</div>
</body>
<script>
var dShop = document.getElementsByClassName("shop")[0];
var dSlider = document.getElementsByClassName("slider")[0];
var dMirror = document.getElementsByClassName("mirror")[0];
var img = document.getElementsByTagName("img")[0];
dShop.onmouseenter = function() {
// 鼠标移入事件
dSlider.style.display = "block";
dMirror.style.display = "block";
}
dShop.onmouseleave = function() {
// 鼠标移出事件
dSlider.style.display = "none";
dMirror.style.display = "none";
}
dShop.onmousemove = function(e) {
// 鼠标移动事件
var x = e.clientX - this.offsetLeft - 75;
var y = e.clientY - this.offsetTop - 75;
// 限制边界
x = (x<0) ? 0 : x;
x = (x>150) ? 150 : x;
y = (y<0) ? 0 : y;
y = (y>150) ? 150 : y;
dSlider.style.left = x + 'px';
dSlider.style.top = y + 'px';
//让大图片进行等比例的移动
var l1 = dSlider.offsetLeft;
var t1 = dSlider.offsetTop;
var w1 = 300;
var w2 = 800;
var l2 = l1 * w2 / w1 * -1;
var t2 = t1 * w2 / w1 * -1;
img.style.left = l2 + 'px';
img.style.top = t2 + 'px';
}
</script>
</html>