实现淘宝放大镜效果
首先应该清楚要实现的效果
然后确定图片、遮盖层的长宽,以及放大效果的长宽,然后实现遮盖层的移动,放大图片的同步,我们可以通过在图片中的半径来计算,下面贴下代码
<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">
<style>
#box{
margin : 50px 100px;
width: 600px;
height: 400px;
}
#img{
position: relative;
width: 200px;
height: 200px;
margin-top: 100px;
display: inline-block;
border: 1px solid #000;
}
#mask{
position: absolute;
width: 100px;
height: 100px;
background: yellow;
opacity: 0.5;
left: 0;
top: 0;
display: none;
}
#section{
display: none;
background-image: url("../assets/logo.png");
background-repeat: no-repeat;
background-size: 600px;
width: 300px;
height: 300px;
}
</style>
<title>Document</title>
</head>
<body>
<div id="box">
<div id="img">
<img src="../assets/logo.png" width="200px">
<div id="mask"></div>
</div>
<div id="section">
</div>
</div>
<script >
let img = document.getElementById("img")
let mask = document.getElementById("mask")
let section = document.getElementById("section")
img.onmousemove = function(e){
mask.style.display = "block"
section.style.display = "inline-block"
//(鼠标的坐标 - 图片的坐标)- 遮盖层的一半 =
鼠标在图片中的坐标 - 遮盖层的一半 =
相对于遮盖层中心层的偏移量
let X = e.pageX - img.offsetLeft - mask.offsetWidth/2
let Y = e.pageY - img.offsetTop - mask.offsetHeight/2
//如果偏移量小于0,取0 ,大于0小于100,
取得到的值,大于100取100,防止遮盖层溢出border
X = X < 0? 0 : (X > img.offsetWidth - mask.offsetWidth ? img.offsetWidth - mask.offsetWidth : X)
Y = Y < 0? 0 : (Y > img.offsetHeight - mask.offsetHeight ? img.offsetHeight - mask.offsetHeight : Y)
mask.style.left = X + "px"
mask.style.top = Y + "px"
section.style.backgroundPositionX = X * -section.offsetWidth/mask.offsetWidth +"px"
section.style.backgroundPositionY = Y * -section.offsetHeight/mask.offsetHeight +"px"
}
img.onmouseleave = function(){
mask.style.display = "none"
section.style.display = "none"
}
</script>
</body>
</html>