js 简易放大镜

样式如图

 

html部分

<div class="box">

   <div class="pic">

        <img src="1.jpeg" alt="">

        <div class="cover"></div>

   </div>

   <div class="detail">

      <img src="1.jpeg" alt="">

   </div>

</div>

 

 

 

css部分

*{

margin: 0;

padding: 0;

}

.box{

position: relative;

width: 400px;

height: 400px;

margin: 50px 0 0 100px;

}

.pic, .pic img{

width: 100%;

height: 100%;

}

.cover{

display: none;

background-image: url(ge.jpg);

width: 150px;

height: 150px;

position: absolute;

left: 0;

top: 0;

background-size: 3px;

opacity: 0.5;

}

.detail{

position: absolute;

left: 400px;

top: 0;

width: 400px;

height: 400px;

overflow: hidden;

}

.detail img{

/* width: 100%;

height: 100%; */

display: none;

position: absolute;

}

 

 

js部分

let pic = document.querySelector(".pic"); //获取左侧盒子

let cover = document.querySelector(".cover"); //获取遮罩层

let detail = document.querySelector(".detail"); //获取右侧盒子

let detailImg = document.querySelector(".detail img"); //获取右侧图片

 

// 鼠标进入左侧图片时显示遮罩层和右侧图片

pic.addEventListener("mouseenter",function(e){

cover.style.display = "block";

detailImg.style.display = "block";

});

// 鼠标离开左侧图片时遮罩层和右侧图片隐藏

pic.addEventListener("mouseleave",function(e){

cover.style.display = "none";

detailImg.style.display = "none";

});

// 鼠标在图片中移动事件监听

pic.addEventListener("mousemove",function(e){

// 获取鼠标坐标

let x = e.clientX;

let y = e.clientY;

 

// 左侧图片的坐标

let left = pic.getBoundingClientRect().left;

let top = pic.getBoundingClientRect().top;

 

// 遮罩层在图片上的偏移量

let cLeft = x - left - cover.offsetWidth/2;

let cTop = y - top - cover.offsetHeight/2;

 

// 判断临界值

// left 和top的最大值

let leftMax = pic.offsetWidth - cover.offsetWidth;

let topMax = pic.offsetHeight - cover.offsetHeight;

 

if(cLeft < 0){

cLeft = 0;

}

if(cLeft > leftMax){

cLeft = leftMax;

}

if(cTop < 0){

cTop = 0;

}

if(cTop>topMax){

cTop = topMax;

}

 

//设置遮罩层的位置

cover.style.left = cLeft + "px";

cover.style.top = cTop + "px";

 

// 显示放大的图片

// detailImg.left/detailImg.width -detail.width = cover.left/pic.width-cover.width;

let detailImgLeft = (detailImg.offsetWidth - detail.offsetWidth )*cLeft/(pic.offsetWidth-cover.offsetWidth);

let detailImgTop = (detailImg.offsetHeight - detail.offsetHeight )*cTop/(pic.offsetHeight-cover.offsetHeight);

 

// 设置右侧放大图片的位置

detailImg.style.left = "-" + detailImgLeft + "px";

detailImg.style.top = "-" + detailImgTop + "px";

 

});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值