我想要写一个放大镜效果的图片效果
相关html代码
<div class="big-ring">
<img src="../images/big-ring.jpg" alt="" width="100%"class="first-img">
<!-- 放大镜圆圈 -->
<div class="move">
<img src="../images/big-ring.jpg" alt="">
</div>
</div>
<script>
// // 获取元素对象
const container=document.querySelector('.big-ring');
const move=document.querySelector('.move');
const bigimg=document.querySelector('.move img');
container.addEventListener('mouseover',function(){
move.classList.remove('hidden');
});
container.addEventListener('mouseout',function(){
move.classList.add('hidden');
})
// 放大镜跟随鼠标移动,绑定container的鼠标移动事件
container.addEventListener('mousemove',function(e){
//获取鼠标距离左侧的便宜
let x=e.clientX;
//获取container距离左侧的偏移
let l=container.offsetLeft;
let moveLeft=x-l-move.offsetWidth/2;
if(moveLeft <=0) moveLeft=0;
let maxLeft=container.offsetWidth-move.offsetWidth;
if(moveLeft>=maxLeft) moveLeft=maxLeft;
// 设置样式
move.style.left=moveLeft+"px";
let bigimgleft = (moveLeft +move.offsetWidth/2) / container.offsetWidth * bigimg.offsetWidth - move.offsetWidth/2;
bigimg.style.left=-bigimgleft+"px";
let y=e.clientY;
// //获取container距离左侧的偏移
let t=container.offsetTop;
let moveTop=y-t-move.offsetHeight/2;
if(moveTop <=0) moveTop=0;
let maxTop=container.offsetHeight-move.offsetHeight;
if(moveTop>=maxTop) moveTop=maxTop;
// // 设置样式
move.style.top=moveTop+"px";
let bigimgTop=(moveTop +move.offsetHeight/2)/container.offsetHeight*bigimg.offsetHeight-move.offsetHeight/2;
bigimg.style.top=-bigimgtop+"px";
});
</script>
css代码
放大镜
*{
margin:0;
padding:0;
}
.body{
display: flex;
justify-content: center;
align-items: center;
height:100vh;
}
.big-ring{
width: 500px;
height:500px;
position: relative;
border:solid 1px #ddd;
}
.move{
width: 300px;
height:300px;
border:solid 10px #000;
position: absolute;
left:0;
top:0;
overflow: hidden;
box-shadow: 0 0 20px #000;
}
.move img{
position:absolute;
left:0;
top:0;
width:800px;
height:800px;
}
.hidden{
opacity: 0;
}
运行结果
放大镜向下移动的时候,放大镜内的内容不对应鼠标所指的内容