<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin:0 ;
padding: 0;
box-sizing: border-box;
}
.product{
width: 450px;
height: 450px;
/*margin: 0 auto;*/
position: relative;
}
.smallImg{
width: 450px;
height: 450px;
background: url(img/mobile.jpg);
background-size: 100% 100%;
position: relative;
}
.zhezhao{
width: 225px;
height: 225px;
background: rgba(0,0,0,0.5);
position: absolute;
}
.bigImg{
width: 450px;
height: 450px;
background: url(img/mobile.jpg);
background-size: 200% 200%;
background-position: 0 0;
position: absolute;
left: 450px;
top: 0;
border: 1px solid #ccc;
display: none;
}
</style>
</head>
<body>
<div class="product">
<div class="smallImg">
</div>
</div>
<script type="text/javascript">
//鼠标进入就会生成一个小的正方形遮罩
var smallImg = document.querySelector('.smallImg')
var product = document.querySelector('.product')
//创建bigImg这个div,用来放置放大的图
var bigImg = document.createElement('div')
bigImg.className = 'bigImg'
product.appendChild(bigImg)
//鼠标进入到产品图需要做的事情,1生成遮罩,2让放大镜显示出来
smallImg.onmouseenter = function(){
var newDiv = document.createElement('div')
newDiv.className = 'zhezhao'
smallImg.appendChild(newDiv)
bigImg.style.display = 'block'
}
//鼠标移动过程需要做的事情,计算出要移动遮罩的x(水平移动),y(数值移动)的大小
smallImg.onmousemove = function(e){
// console.log(e)
var x = e.clientX - product.offsetLeft -112.5
var y = e.clientY - product.offsetTop - 112.5
if(x<0){
x = 0
}
if(x>225){
x = 225
}
if(y<0){
y = 0
}
if(y>225){
y = 225
}
//移动遮罩的位置
var zhezhao = document.querySelector('.zhezhao')
zhezhao.style.left = x + 'px';
zhezhao.style.top = y +'px';
//移动放大镜背景图片的位置
bigImg.style.backgroundPositionX = -2*x +'px';
bigImg.style.backgroundPositionY = -2*y + 'px';
}
//鼠标移出去需要还原的内容
smallImg.onmouseleave = function(){
// smallImg.removeChild(document.querySelector('.zhezhao'))
smallImg.innerHTML = ''
bigImg.style.display = 'none'
}
</script>
</body>
</html>