JS === 简易放大镜

<!DOCTYPE html>
<html>
  <head>
  <title></title>
  <style>
    .box{width: 1000px;height: 600px;border:1px solid #ccc;margin:50px auto;}
    .small{float: left;width: 300px;height: 300px;border:1px solid #000;position: relative;}
    .big{float: left;width: 300px;height: 300px;overflow: hidden;border:1px solid #eee;margin-left:80px;margin-top:30px;display: none;position: relative;}
    .mark{position: absolute;width: 80px;height: 80px;background:yellow;opacity: 0.6;left:0;top:0;display: none}
    .big img{position: absolute;}
  </style>
  </head>


  <body>
    <div class="box">    //最外边大盒子
      <div class="small">     //小图片盒子   小图片大小=小图片盒子大小
        <img src= "1.jpg">   //小图片
        <div class="mark"></div>   //小图片放大镜
      </div>
      <div class="big">  // 大图片盒子
        <img src="2.jpg">    //大图片
      </div>
    </div>

<script type="text/javascript">
    var box = document.querySelector(".box")
    var small = document.querySelector(".small");
    var big = document.querySelector(".big");
    var bigimg = big.children[0];
    var mark = document.querySelector(".mark")
    

  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(evt){
  //鼠标在盒子中心
    var x = evt.clientX - box.offsetLeft - mark.offsetWidth/2;
    var y = evt.clientY - box.offsetTop - mark.offsetHeight/2;

  //让mark 放大镜 始终存在在 small 里面
    if(x<0){ 
      x=0;
    }else if(x > small.offsetWidth - mark.offsetWidth){
      x = small.offsetWidth - mark.offsetWidth;
    }

    if(y <0 ){
      y=0;
    }else if (y > small.offsetHeight - mark.offsetHeight){
      y = small.offsetHeight - mark.offsetHeight
    }
    mark.style.left = x + "px";
    mark.style.top = y +"px"

    

    var imgleft = -x *2;   //在这里比例 : 小图片与大图片比例 是 1:2  放大镜移动的距离与大图片移动的距离之间的比例 也为 1:2
    var imgtop = -y*2;

   

  // 下面这段代码== 为了避免大图片移动过程中会出现大量空白

  // 大图片向左边移动的距离 如果超过 盒子的宽度,则会出现大量空白 

  //例如 大图片向左移动了 500px(left : -500px),此时盒子大小是400px ,则会出现大量空白

  if(imgleft < -big.offsetWidth){      //(-500 < -400)==  移动的left始终是 -400
    imgleft = -big.offsetWidth;
  }else{
    imgleft = imgleft;
    }

  if(imgtop < -big.offsetHeight){
    imgtop = -big.offsetHeight;
  }else{
    imgtop =imgtop;
  }


  bigimg.style.left = imgleft + "px";   //大图片移动的坐标
  bigimg.style.top = imgtop + "px";

  }

</script>

</body>
</html>

总结:

1.几个事件

onmouseover == 鼠标移动上去的时候

onmouseout == 鼠标移出的时候

onmousemove == 鼠标移动

file:///E:/%E6%9E%97%E9%9C%9C%E9%9B%AAJS/all%E7%BB%83%E4%B9%A0ppt/%E6%94%BE%E5%A4%A7%E9%95%9C.html

猜你喜欢

转载自www.cnblogs.com/rabbit-lin0903/p/11184482.html
今日推荐