如何用原生js实现放大镜特效

本文介绍了一种使用HTML、CSS及JavaScript实现的鼠标悬停显示大图效果的方法。通过设置不同状态下的显示与隐藏,结合鼠标移动位置计算,使得用户在预览小图时可以查看到放大的局部细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 <!DOCTYPE html>
 <html>
 <head>
 <meta charset="UTF-8">
 <title></title>
 <style type="text/css">
 #box{
 width: 1000px;
 height: 400px;
 border: 1px solid salmon;
 position: relative;
 margin: 50px auto;
 }
 #small{
 width: 350px;
 height: 350px;
 position: absolute;
 border: 1px solid slateblue;
 }
 #big{
 width: 350px;
 height: 350px;
 position: absolute;
 border: 1px solid slateblue;
 left: 352px;
 overflow: hidden;
 display: none;
 }
 #mark{
 width: 153px;
 height: 153px;
 background-color: rgba(0,0,0,0.5);
 position: absolute;
 display: none;
 }
 .limg{
 position: absolute;
 }
 </style>
 </head>
 <body>
 <div id="box">
 <div id="small">
 <div id="mark"></div>
 <img src="img/product-s4-m.jpg"/>
 </div>
 <div id="big">
 <img src="img/product-s4-l.jpg" class="limg" id="img2"/>
 </div>
 </div>
 </body>
 <script type="text/javascript">
  
 function demo(str){
 return str ? document.getElementById(str) : null;
 }
 var big = demo("big");
 var small = demo("small");
 var mark = demo("mark");
 var box = demo("box");
 small.onmouseover = function(){
 mark.style.display = "block";
 big.style.display = "block";
 }
 small.onmouseout = function(){
 mark.style.display = "none";
 big.style.display = "none";
 }
 small.onmousemove = function(eve){
 eve = window.event || eve;
 var x = eve.clientX - small.parentElement.offsetLeft - mark.clientWidth/2;
 var y = eve.clientY -small.parentElement.offsetTop - mark.clientHeight/2;
  
 //限制mark出框
 if (x<0) {
 x = 0;
 }
 if (y<0) {
 y = 0;
 }
 if (x > small.clientWidth-mark.clientWidth) {
 x = small.clientWidth-mark.clientWidth;
 }
 if (y > small.clientHeight - mark.clientHeight) {
 y = small.clientHeight - mark.clientHeight;
 }
  
 mark.style.left = x + "px";
 mark.style.top = y + "px";
 //获得比例
 var limg = document.getElementsByClassName("limg")[0];
 var img2 = document.getElementById("img2");
 console.log(limg.clientWidth);
 var scare = (limg.height - big.clientHeight)/(small.clientHeight - mark.clientHeight);
 limg.style.left = - x * scare + "px";
 limg.style.top = - y * scare + "px";
  
  
 }
  
 </script>
 </html>
  

 

 

 

转载于:https://www.cnblogs.com/chuanzhou/p/7212143.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值