时间:2022-03-31 08:34:07 | 栏目:JavaScript代码 | 点击:次
本文实例为大家分享了JavaScript实现商品放大镜的具体代码,供大家参考,具体内容如下
HTML+CSS部分:
<style> .small{ position: relative; width: 400px; height: 450px; border: 1px solid #ccc; } .small img{ width: 100%; height: 100%; } .small .mask{ position: absolute; left: 0; top: 0; width: 300px; height: 300px; background-color: rgba(0, 255, 0, .2); } .big{ position: absolute; left: 450px; top: 8px; width: 550px; height: 550px; border: 1px solid #ccc; overflow: hidden; display: none; } .big img{ position: absolute; left: 0; top: 0; } </style> <body> <div class="small"> <img src="./img/small.jpg"> <div class="mask"></div> </div> <div class="big"> <img src="./img/big.jpg"> </div> </body>
JS部分:
<script> var small=document.querySelector('.small'); var mask=document.querySelector('.mask'); var big=document.querySelector('.big'); var bigImg=document.querySelector('.big>img'); // 拿到大图的宽高 var bigWidth=bigImg.offsetWidth; var bigHeight=bigImg.offsetHeight; // function move(e){ var x=e.pageX - this.offsetLeft; var y=e.pageY - this.offsetTop; console.log(x,y); // 移动遮罩位置 var maskHeight = mask.offsetHeight/2; var maskWidth = mask.offsetWidth/2; mask.style.left = x - maskWidth+'px'; mask.style.top = y - maskHeight+'px'; // 限制遮罩的移动范围 // console.log('mask.offsetTop',mask.offsetTop); // console.log('mask.offsetLeft',mask.offsetLeft); var maxLeft=small.offsetWidth - mask.offsetWidth; if(mask.offsetTop<0){ mask.style.top=0; } if(mask.offsetLeft > small.offsetWidth - mask.offsetWidth){ mask.style.left =maxLeft+'px'; } if(mask.offsetLeft<0){ mask.style.left = 0; } if(mask.offsetTop > small.offsetHeight - mask.offsetHeight){ mask.style.top = small.offsetHeight - mask.offsetHeight + 'px'; } // bigImg 大图 big 大盒子 大图的移动 // (bigImg.offsetWidth - big.offsetWidth) / (samll.offsetWidtth - mask.offsetWidth) // 大图的最大移动距离 = - 遮罩的移动距离 * 大图的最大距离 / 遮罩的最大移动距离 bigImg.style.left = -mask.offsetLeft*(bigImg.offsetWidth - big.offsetWidth) / (small.offsetWidth - mask.offsetWidth)+"px"; bigImg.style.top = -mask.offsetTop*(bigImg.offsetHeight - big.offsetHeight) / (small.offsetHeight - mask.offsetHeight)+"px"; } // 小图上移动遮罩 small.addEventListener('mousemove',move); small.addEventListener('mouseover',function(){ big.style.display='block'; mask.style.display='block'; }) small.addEventListener('mouseout',function(){ big.style.display='none'; mask.style.display='none'; }) </script>
效果演示: