适用于电商项目的放大镜效果
2020-03-01 本文已影响0人
Fanny
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>放大镜效果</title>
<style>
* {
margin: 0;
padding: 0;
}
.bigbox {
width: 400px;
height: 400px;
border: 1px solid #ccc;
position: relative;
left: 30px;
top: 30px;
}
.smallimg {
width: 400px;
height: 400px;
position: relative;
z-index: 2;
}
.maskbox {
position: absolute;
z-index: 999;
background-color: yellow;
opacity: .3;
left: 0px;
top: 0px;
width: 200px;
height: 200px;
display: none;
}
.outbox {
position: absolute;
left: 420px;
top: 0px;
width: 800px;
height: 800px;
border: 1px solid #ccc;
display: none;
overflow: hidden;
}
.bigimg {
position: relative;
left: 0px;
top: 0px;
width: 1600px;
height: 1600px;
}
</style>
</head>
<body>
<div class="bigbox">
<img class="smallimg" src="http://img0.imgtn.bdimg.com/it/u=2234101414,3057589362&fm=26&gp=0.jpg" alt="">
<div class="maskbox"></div>
<div class="outbox"><img class="bigimg" src="http://img0.imgtn.bdimg.com/it/u=2234101414,3057589362&fm=26&gp=0.jpg" alt=""></div>
</div>
</body>
</html>
<script>
var bigbox = document.getElementsByClassName('bigbox')[0];
var maskbox = document.getElementsByClassName('maskbox')[0];
var outbox = document.getElementsByClassName('outbox')[0];
var bigimg = document.getElementsByClassName('bigimg')[0];
bigbox.onmouseover = function (e) {
maskbox.style.display = 'block';
outbox.style.display = 'block';
bigbox.onmousemove = function (e) {
e = e || window.event
let x = e.pageX - bigbox.offsetLeft - (maskbox.offsetWidth / 2)
let y = e.pageY - bigbox.offsetTop - (maskbox.offsetHeight / 2)
console.log(x, y);
//边界检测
var maskleft = bigbox.offsetWidth - maskbox.offsetWidth
var masktop = bigbox.offsetHeight - maskbox.offsetHeight
x = x > 0 ? x : 0
x = x > maskleft ? maskleft : x
y = y > 0 ? y : 0
y = y > masktop ? masktop : y
maskbox.style.left = x + 'px'
maskbox.style.top = y + 'px'
bigimg.style.left = -(outbox.offsetWidth / maskbox.offsetWidth) * x + "px"
bigimg.style.top = -(outbox.offsetHeight / maskbox.offsetHeight) * y + "px"
}
}
bigbox.onmouseout = function (e) {
maskbox.style.display = 'none';
outbox.style.display = 'none';
}
</script>