cursor:point 出来是小手指
cursor:move出来是十字箭头移动符号
event.clientX、event.clientY
鼠标相对于浏览器窗口可视区域的X,Y坐标(窗口坐标),可视区域不包括工具栏和滚动条。IE事件和标准事件都定义了这2个属性
event.offsetX、event.offsetY
鼠标相对于事件源元素(srcElement)的X,Y坐标,只有IE事件有这2个属性,标准事件没有对应的属性。
event.screenX、event.screenY
鼠标相对于用户显示器屏幕左上角的X,Y坐标。标准事件和IE事件都定义了这2个属性
全部代码:
<!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>
* {
margin: 0;
padding: 0;
}
#box {
width: 400px;
height: 225px;
margin: 100px;
border: 1px solid #ccc;
position: relative;
}
#small {
position: relative;
}
#small img {
width: 400px;
height: 100%;
}
#mask {
width: 200px;
height: 120px;
background: rgba(255, 255, 0, 0.4);
position: absolute;
top: 0;
left: 0;
cursor: move;
display: none;
}
#big {
position: absolute;
top: 0;
left: 560px;
width: 400px;
height: 225px;
overflow: hidden;
display: none;
border: 1px solid #ccc;
}
#big img {
width: 800px;
}
</style>
</head>
<body>
<div id="box">
<div id="small">
<img src="./桌面壁纸.jpg" alt="">
<div id="mask"></div>
</div>
<div id="big">
<img id="b-img" src="./桌面壁纸.jpg" alt="">
</div>
</div>
<script>
var box = document.getElementById("box");
var small = document.getElementById("small");
var mask = document.getElementById("mask");
var big = document.getElementById("big");
var bImg = document.getElementById("b-img");
// 显示放大区域和原图
//box被鼠标进入之后发生:
small.onmouseenter = function () {
mask.style.display = 'block'
big.style.display = 'block'
}
// 隐藏放大区域和原图
small.onmouseleave = function () {
mask.style.display = 'none'
big.style.display = 'none'
}
small.onmousemove = function (e) {
// 确定mask坐标随鼠标坐标的改变
var x = e.clientX - mask.offsetWidth / 2 - 100
var y = e.clientY - mask.offsetHeight / 2 - 100
// 确定mask边界
var x = x < 0 ? 0 : x
var y = y < 0 ? 0 : y
var x = x > small.offsetWidth - mask.offsetWidth ? small.offsetWidth - mask.offsetWidth : x
var y = y > small.offsetHeight - mask.offsetHeight ? small.offsetHeight - mask.offsetHeight : y
//mask移动,left top有定位的时候用
mask.style.left = x + 'px'
mask.style.top = y + 'px'
//大图移动
var b_x = x * (bImg.offsetWidth - big.offsetWidth) / (small.offsetWidth - mask.offsetWidth)
var b_y = y * (bImg.offsetHeight - big.offsetHeight) / (small.offsetHeight - mask.offsetHeight)
//marginleft margitop没有定位的时候用
bImg.style.marginLeft = -b_x + 'px'
bImg.style.marginTop = -b_y + 'px'
}
</script>
</body>
</html>