将鼠标移动至图片区域可放大预览

效果图:

js仿淘宝商品放大预览功能

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    *{padding:0; margin:0;}
    #img1{width:300px; height:200px;}
    #sp1{width:60px; height:40px; position: absolute; left:0; top:0; background: rgba(62, 55, 58, 0.4)
    }
    #img2{width:2250px; height:1500px; position: absolute;}
    div{width:450px; height:300px; position: absolute; left:310px; top:0; overflow: hidden; border:2px solid black; display: none;}
  </style>
  <script>
    window.onload=function(){
      var img1 = document.getElementById('img1');
      var img2 = document.getElementById('img2');
      var sp = document.getElementById('sp1');
      var oBox = document.getElementById('box');
      sp.onmouseover=function(){
        oBox.style.display='block';
      };
      sp.onmouseout=function(){
        oBox.style.display='none';
      };
      document.onmousemove=function(ev){
        var x = (ev.clientX || event.clientX)-sp.offsetWidth/2;
        var y = (ev.clientY || event.clientY)-sp.offsetHeight/2;
        if((ev.clientX || event.clientX)<sp.offsetWidth/2){
          x = 0;
        }
        if((ev.clientX || event.clientX)>img1.offsetWidth-sp.offsetWidth/2){
          x = img1.offsetWidth-sp.offsetWidth;
        }
        if((ev.clientY || event.clientY)<sp.offsetHeight/2){
          y = 0;
        }if((ev.clientY || event.clientY)>img1.offsetHeight-sp.offsetHeight/2){
          y = img1.offsetHeight-sp.offsetHeight;
        }
        if((ev.clientX || event.clientX)<300 && (ev.clientY || event.clientY)<200) {
          sp.style.left = x + 'px';
          sp.style.top = y + 'px';
          img2.style.left = -x * (img2.offsetWidth / img1.offsetWidth) + 'px';
          img2.style.top = -y * (img2.offsetHeight / img1.offsetHeight) + 'px';
        }
      }
    }
  </script>
</head>
<body>
<img src="/UploadFiles/2021-04-02/timg">

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!

标签:
js,图片放大预览,js图片放大预览效果,放大镜效果

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
狼山资源网 Copyright www.pvsay.com

评论“js仿淘宝商品放大预览功能”

暂无“js仿淘宝商品放大预览功能”评论...