欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-29 22:59:05
将鼠标移动至图片区域可放大预览 效果图: 代码如下: <...

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

效果图:

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="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1489083204637&di=244fe324db033fc826de48e90d2373f0&imgtype=0&src=http%3a%2f%2fpic2015.5442.com%2f2016%2f0328%2f025%2f5.jpg%2521960.jpg
" alt="" id="img1">
<span id="sp1"></span>
<div id="box">
  <img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1489083204637&di=244fe324db033fc826de48e90d2373f0&imgtype=0&src=http%3a%2f%2fpic2015.5442.com%2f2016%2f0328%2f025%2f5.jpg%2521960.jpg
" alt="" id="img2">
</div>
</body>
</html>

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