原生js 放大镜效果
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 350px;
height: 350px;
margin: 100px;
border: 1px solid #ccc;
position: relative;
}
.big {
width: 400px;
height: 400px;
position: absolute;
top: 0;
left: 360px;
border: 1px solid #ccc;
overflow: hidden;
display: none;
}
.mask {
width: 175px;
height: 175px;
background: rgba(255, 255, 0, 0.4);
position: absolute;
top: 0;
left: 0;
cursor: move;
display: none;
}
.small {
position: relative;
}
.box img {
vertical-align: top;
}
#bigBox img {
position: absolute;
}
</style>
</head>
<body>
<div class="box" id="box">
<div id="smallBox" class="small">
<img src="images/001.jpg" width="350" alt=""/>
<div id="mask" class="mask"></div>
</div>
<div id="bigBox" class="big">
<img src="images/0001.jpg" width="800" alt=""/>
</div>
</div>
<script>
//找对象
var box = document.getElementById('box');
var smallBox = document.getElementById('smallBox');
var mask = document.getElementById('mask');
var bigBox = document.getElementById('bigBox');
var bigImg = bigBox.children[0];
//给small注册鼠标移入事件
smallBox.onmouseover = function () {
mask.style.display = "block";
bigBox.style.display = "block";
}
smallBox.onmouseout = function () {
mask.style.display = "none";
bigBox.style.display = "none";
}
//计算设置mask的位置
smallBox.onmousemove = function (e) {
var x = getPage(e).x - box.offsetLeft - mask.offsetWidth / 2;
var y = getPage(e).y - box.offsetTop - mask.offsetHeight / 2;
var maxX = smallBox.offsetWidth - mask.offsetWidth;
var maxY = smallBox.offsetHeight - mask.offsetHeight;
if (x < 0) {
x = 0;
} else if (x > maxX) {
x = maxX
}
if (y < 0) {
y = 0;
} else if (y > maxY) {
y = maxY
}
mask.style.left = x + "px";
mask.style.top = y + "px";
var rateX = x / maxX;
var rateY = y / maxY;
bigImg.style.left = -rateX * (bigImg.offsetWidth - bigBox.offsetWidth) + "px";
bigImg.style.top = -rateY * (bigImg.offsetHeight - bigBox.offsetHeight) + "px";
}
</script>
</body>
</html>