Jq实现放大镜效果

2018-11-07  本文已影响0人  立的flag一直在倒

HTML

  <div class="wrapper">
    <div class="imgbox">
      <img src="http://www.jq22.com/demo/jpgZoo20160421/images/img01.jpg">
      <div class="hoverbox"></div>
    </div>
    <div class="showbox">
      <img src="http://www.jq22.com/demo/jpgZoo20160421/images/img01.jpg">
    </div>
  </div>

CSS

  <style>
    .wrapper {
      position: relative;
      margin-left: 100px;
    }

    .imgbox {
      width: 300px;
      height: 300px;
      border: 1px solid #000;
    }

    .imgbox img {
      width: 300px;
      height: 300px;
      vertical-align: top;
    }

    .showbox {
      display: none;
      position: absolute;
      left: 400px;
      top: 0;
      width: 400px;
      height: 300px;
      border: 1px solid #ccc;
      overflow: hidden;
    }
    .showbox img {
      position: absolute;
      width: 1200px;
    }
    .hoverbox {
      display: none;
      position: absolute;
      top: 0;
      width: 100px;
      height: 75px;
      border: 1px solid #09f;
      cursor: move;
      z-index: 10;
      background: #09f;
    }
  </style>

JS

  <script>
    function Zoomhover(img, hoverbox, showImg) {
      var imgleft = img.offset().left;
      var imgtop = img.offset().top;
      var hoverWidth = hoverbox.width();
      var hoverHeight = hoverbox.height();
      $(".imgbox > img, .hoverbox").mouseover(function (e) {
        var x = e.pageX;
        var y = e.pageY;
        $(".hoverbox, .showbox").show();
        hoverbox.css("opacity", "0.3");
        Zoom(img, hoverbox, showImg, imgleft, imgtop, x, y, hoverWidth, hoverHeight);
      }).mousemove(function (e) {
        var x = e.pageX;
        var y = e.pageY;
        Zoom(img, hoverbox, showImg, imgleft, imgtop, x, y, hoverWidth, hoverHeight);
      }).mouseout(function (e) {
        showImg.parent().hide();
        hoverbox.hide();
      });
    }


    function Zoom(img, hoverbox, showImg, imgleft, imgtop, x, y, hoverWidth, hoverHeight) {
      var moveX = x - imgleft - (hoverWidth / 2);
      var moveY = y - imgtop - (hoverHeight / 2);

      moveX = moveX < 0 ? 0 : moveX;
      moveX = moveX > img.width() - hoverWidth ? img.width() - hoverWidth : moveX;
      moveY = moveY < 0 ? 0 : moveY;
      moveY = moveY > img.height() - hoverHeight ? img.height() - hoverHeight : moveY;

      // 设置显示比例
      var proportionX = showImg.width() / img.width();
      var proportionY = showImg.height() / img.height();
      showImg.css({
        left: -(moveX * proportionX),
        top: -(moveY * proportionY)
      });
      hoverbox.css({
        left: moveX,
        top: moveY
      });
    }
    $(function () {
      Zoomhover($(".imgbox img"), $(".hoverbox"), $(".showbox img"));
    });
  </script>
上一篇下一篇

猜你喜欢

热点阅读