需求
html代码
<div id="bigbox">
<div id="box1">
<img src="C:\Users\20265\Pictures\Saved Pictures\p2184395860.webp" alt="">
<span id="lens"></span>
</div>
<div id="box2">
<img src="C:\Users\20265\Pictures\Saved Pictures\p2184395860.webp" alt="" id="picImg">
</div>
</div>
css代码
*{
margin: 0;
padding: 0;
}
#bigbox{
width: 1100px;
height: 600px;
margin: 50px auto;
}
#box1{
position: relative;
height: 600px;
width: 524px;
float: left;
margin-right: 10px;
}
#box1 img{
height: 600px;
width: 524px;
}
#box1 span{
position: absolute;
width: 262px;
height: 300px;
background: #fff;
border: 1px solid yellow;
opacity: .5;
top: 0;
left: 0;
display: none;
}
#box2{
position: relative;
height: 600px;
width: 524px;
overflow: hidden;
display: none;
float: left;
}
#box2 img{
height: 1200px;
width:1048px;
position: absolute;
left: 0;
top: 0;
}
JavaScript代码
var bigbox = document.getElementById('bigbox')
var box1 = document.getElementById('box1')
var lens = document.getElementById('lens')
var box2 = document.getElementById('box2')
var picImg = document.getElementById('picImg')
box1.onmouseover = function(){
lens.style.display = 'block'
box2.style.display = 'block'
}
box1.onmousemove = function(e){
var x = e.clientX - bigbox.offsetLeft - lens.offsetWidth/2
var y = e.clientY - bigbox.offsetTop - lens.offsetHeight/2
if(x<0){
x=0;
}else if(x>box1.offsetWidth - lens.offsetWidth){
x=box1.offsetWidth - lens.offsetWidth
}
if(y<0){
y=0
}else if(y>box1.offsetHeight - lens.offsetHeight){
x=box1.offsetHeight - lens.offsetHeight
}
lens.style.left = x +'px'
lens.style.top = y +'px'
picImg.style.left = -x*2+'px'
picImg.style.top = -y*2+'px'
}
box1.onmouseout = function(){
lens.style.display = 'none'
box2.style.display = 'none'
}
效果样式
实现原理
- 先将盒子制作完成,左右两边为两个大小相同的盒子,同时在第一个盒子里添加一个内联,即阴影部分
- 第二个盒子的图片是第一个盒子的2.4倍
- 将阴影与大图片display设置成none,通过鼠标移入移出事件将它们转化为block
- 在给阴影加上鼠标移动事件同时将它的left与top值被赋值
- 在第五步的基础上给大图片的left与top值赋值,方向相反需要加负号,同时乘2.4