在浏览网页时,我们经常会看到各种各样放大镜效果,那么小熊今天就来模拟一下该效果。
我们要实现的功能为:当鼠标经过小图片时, 会在小图片上显示一个小的遮挡层并将遮挡层里面的内容放大显示,当鼠标离开时,让遮挡层和放大显示的图片消失掉。
实现思路为:
- 先让小的遮挡层跟随鼠标移动。因为遮挡层坐标以父盒子为准,所以把鼠标坐标给遮挡层不合适。首先是获得鼠标在盒子的坐标,之后把数值给遮挡层做为left 和top值。但是为了美观,在这里可以将遮挡层中间的坐标给鼠标,即让遮挡层位置再减去盒子自身高度和宽度的一半。
- 然后用到鼠标移动事件,但是还是在小图片盒子内移动。并且遮挡层不能超出小图片盒子范围。如果小于零,就把坐标设置为0,如果大于遮挡层最大的移动距离,就把坐标设置为最大的移动距离
- 遮挡层的最大移动距离: 小图片盒子宽度 减去 遮挡层盒子宽度
- 再得到放大后图片的最大移动距离:遮罩层的最大移动距离*大图片最大移动距离/小图片最大移动距离
- 最后,根据比例关系,得到移动遮挡层,大图片跟随移动功能。
实现代码为:
<!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>
.box1{
position: relative;
float: left;
width:284px;
height:240px;
margin-top: 100px;
border: 1px solid #ccc;
}
.box2{
position: absolute;
top: -80px;
left: -10px;
display: none;
margin-left : 300px;
width: 400px;
height: 400px;
border: 1px solid #ccc;
overflow: hidden;
}
.mask{
display: none;
width: 200px;
height: 200px;
background-color: cyan;
opacity: .5;
position: absolute;
top: 0px;
left: 0px;
cursor: move;
}
.photo{
position:absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="box1">
<img src="fj.jpg" alt="" width='284px' height = '240px'>
<div class="mask"></div>
<div class="box2">
<img src="fj.jpg" alt="" width='568px' height = '480px' class = 'photo'>
</div>
</div>
<script>
var box = document.querySelectorAll('div');
var photo = document.querySelector('.photo')
box[0].addEventListener('mouseover',function(){
box[1].style.display = 'block';
box[2].style.display = 'block';
})
box[0].addEventListener('mouseout',function(){
box[1].style.display = 'none';
box[2].style.display = 'none';
})
//鼠标移动,让遮罩层跟着鼠标移动
box[0].addEventListener('mousemove',function(e){
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
//遮罩层移动的距离
var maskX = x - box[1].offsetWidth/2;
var maskY = y - box[1].offsetHeight/2;
//上下左右的限制条件
if(maskX <= 0){
maskX = 0;
}else if(maskX>=box[0].offsetWidth - box[1].offsetWidth){
maskX = box[0].offsetWidth - box[1].offsetWidth;
}
if(maskY <= 0){
maskY = 0;
}else if(maskY>=box[0].offsetHeight - box[1].offsetHeight){
maskY = box[0].offsetHeight - box[1].offsetHeight;
}
//
box[1].style.left = maskX + 'px';
box[1].style.top = maskY + 'px';
//大图的移动距离 = 遮罩层的移动距离*大图片最大移动距离/小图片最大移动距离
var maskMaxX = box[0].offsetWidth - box[1].offsetWidth;
console.log(maskMaxX);
var photoMaxX = photo.offsetWidth - box[2].offsetWidth;
console.log(photoMaxX);
var maskMaxY = box[0].offsetHeight - box[1].offsetHeight
var photoMaxY = photo.offsetHeight - box[2].offsetHeight;
var photoX =maskX*photoMaxX/maskMaxX;
var photoY =maskY*photoMaxY/maskMaxY;
photo.style.left = -photoX + 'px'
photo.style.top = -photoY + 'px'
})
</script>
</body>
</html>
实现效果为:
你学会了吗?