一、Demo
<1>.要求
1.鼠标移至图片上方,鼠标周围出现黄色的的正方形框,黄色矩形框会随着鼠标的移动而移动;
2.将黄色正方形框里的内容的长和宽均放大2.4倍,并在图片右边进行显示。
<2>.功能
实现小图大化,放大2.4倍观看
二、实现原理
思路:html和css部分主要负责2张图的位置和大图、阴影的隐藏效果
JS部分难点在于:如何控制鼠标拖动阴影的同时,大图同步进行移动
答:计算:当前鼠标的位置-盒子距离浏览器左侧的偏移-阴影宽度的一半
三、代码
<1>.Html部分
<!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>放大镜效果</title>
<link rel="stylesheet" href="./index.css">
</head>
<body>
<div class="main" id="main">
<div class="small l" id="small">
<img src="./apex.png" alt="">
<span class="shade" id="shade"></span>
</div>
<div class="big l" id="big">
<img src="./apex 1080px.jpg" alt="" id="picture">
</div>
</div>
<script src="./index.js"></script>
</body>
</html>
<2>.Css部分
*{
margin: 0;
padding: 0;
}
.l{
float: left;
}
.main{
margin: 150px;
overflow: hidden;
}
.small{
position: relative;
width: 450px;
height: 450px;
}
.small img{
width: 100%;
height: 100%;
}
.small span{
display: none;
position: absolute;
left: 0;
top: 0;
width: 225px;
height: 225px;
background: #fff;
opacity: .5;
}
.big{
position: relative;
display: none;
margin-left: 30px;
width: 450px;
height: 450px;
overflow: hidden;
}
.big img{
position:absolute;
left: 0;
top: 0;
}
<3>.Js部分
var small = document.getElementById('small');//获取小盒子
var shade = document.getElementById('shade');//获取阴影
var big = document.getElementById('big');//获取大盒子
var main = document.getElementById('main');
var picture = document.getElementById('picture');
small.onmouseover = function(){ //给小盒子加入鼠标移入事件,让阴影和大盒子显示
shade.style.display = 'block';
big.style.display = 'block';
}
small.onmousemove = function(index){
//当前鼠标的位置-盒子距离浏览器左侧的偏移-阴影宽度的一半
var x = index.clientX - main.offsetLeft - shade.offsetWidth/2;
var y = index.clientY - main.offsetTop - shade.offsetHeight/2;
if(y<0){ //固定阴影位置
y=0;
}else if(y > small.offsetHeight - shade.offsetHeight){
y = small.offsetHeight - shade.offsetHeight
}
shade.style.left = x+'px'; //阴影位置
shade.style.top = y+'px';
picture.style.left = -x *2.4 +'px'; //大图移动
picture.style.top = -y *2.4 +'px';
}
small.onmouseout= function(){
lens.style.display ='none';
big.style.display ='none';
}
四、效果展示
放大镜效果