>  기사  >  웹 프론트엔드  >  돋보기 효과를 얻으려면 jquery를 사용하세요_jquery

돋보기 효과를 얻으려면 jquery를 사용하세요_jquery

WBOY
WBOY원래의
2016-05-16 16:38:001489검색

구현원리

먼저 돋보기 효과를 얻는 방법을 설명하겠습니다.

방법 1: 픽셀이 높은 큰 그림을 준비합니다. 원본 그림 위에 마우스를 놓으면 큰 그림의 해당 위치를 로드하여 표시합니다.

방법 2: 원본 이미지를 확대합니다. 즉, 원본 이미지의 길이와 너비를 조정합니다.

위에서는 돋보기 효과를 얻기 위한 두 가지 방법을 소개했습니다. 다음으로 위의 두 가지 방법을 jQuery 플러그인에 적용합니다.

먼저 원본 이미지 객체를 표시하려면 img 요소가 필요하고, 표시 상자에 큰 이미지 객체가 저장되는 컨테이너가 필요합니다. 원본 이미지 위로 마우스를 이동하면 큰 이미지의 절대 위치 지정으로 해당 부분이 표시되어 돋보기와 같은 효과를 얻을 수 있습니다.

다음으로 Index.html 페이지를 정의해 보겠습니다. 구체적인 구현은 다음과 같습니다.

<!DOCTYPE html>
<html>
<head>
<title>放大镜效果</title>
<meta charset="utf-8"/>
<meta name="description" content=""/>
<meta name="keywords" content=""/>
<link type="text/css" rel="stylesheet" href="css/reset.css"/>
<link type="text/css" rel="stylesheet" href="css/main.css"/>
<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
<script type="text/javascript" src="js/jquery.imageZoom.js"></script>


</head>
<body> 
<div class="magnify">
<div class="large"></div>
<img class="small" src="images/iphone.jpg" width="200" />
</div>

<div class="magnify_02">
<div class="large_02"></div>
<img class="small_02" src="images/img5.jpg" width="400"/>
</div>
<script type="text/javascript">
$(function(){

  $(".magnify").hover(function(){
      $.fn.imageZoom({
    small :"small",
    large : "large",
    magnify: "magnify"
    });

  },function(){})

  $(".magnify_02").hover(function(){
    $.fn.imageZoom({
    small : "small_02",
    large : "large_02",
    magnify: "magnify_02"
    });

  },function(){})

})
</script>
</body>
</html>

CSS 스타일:

.magnify {width: 200px; margin: 50px auto; position: relative;}
.large {width: 175px; height: 175px;position: absolute;border-radius: 100%;z-index:99;box-shadow: 0 0 0 7px rgba(255, 255, 255, 0.85), 0 0 7px 7px rgba(0, 0, 0, 0.25), inset 0 0 40px 2px rgba(0, 0, 0, 0.25);background: url('../images/iphone.jpg') no-repeat;display: none;}
.small { display: block; }

.magnify_02 {width: 400px; margin: 50px auto; position: relative;}
.large_02 {width: 175px; height: 175px;position: absolute;border-radius: 100%;z-index:99;box-shadow: 0 0 0 7px rgba(255, 255, 255, 0.85), 0 0 7px 7px rgba(0, 0, 0, 0.25), inset 0 0 40px 2px rgba(0, 0, 0, 0.25);background: url('../images/iphone.jpg') no-repeat;display: none;}
.small_02 { display: block; }

마우스무브 이벤트
다음으로, 돋보기 효과를 얻기 위해 jQuery 플러그인을 사용합니다. 마우스가 작은 개체 위로 이동하면 큰 이미지의 해당 위치가 큰 개체에 표시되므로 mousemove 이벤트가 발생합니다. mousemove 이벤트에 대한 청취 방법을 구현해야 합니다.

jquery.imagezoom.js 플러그인 구현:

(function($) {

  $.fn.imageZoom = function(options) {

    var defaults = {
      scaling: 0.3,
      small :"small",
      large : "large",
      magnify:"magnify"


    };

    options = $.extend(defaults, options),
      native_width = 0,
      native_height = 0,
      current_width = 0,
      current_height = 0,

       magnify="."+options.magnify;

       small="."+options.small;
       $small=$(small);

       large="."+options.large;
       $large=$(large);

     $(magnify).mousemove(function(e) {

        var image_object = new Image();

        image_object.src = $small.attr('src');

      if(!+[1,]) {

        native_height = image_object.height;

        native_width = image_object.width; 

        } 
        else {
          image_object.onload = function() {  
          image_object.onload = null;
          native_height = image_object.height;
          native_width = image_object.width;
          }
        }
        current_height = $small.height();
        current_width = $small.width();
        var magnify_offset = $(this).offset();
        var mx = e.pageX - magnify_offset.left;
        var my = e.pageY - magnify_offset.top;

        if (mx < $(this).width() && my <$(this).height() && mx > 0 && my > 0) {

          $large.fadeIn(100);

        } else {
          $large.fadeOut(100);
        }
        if ($large.is(":visible")) {
          var rx = Math.round(mx / $small.width() * native_width - $large.width() / 2) * -1,
            ry = Math.round(my / $small.height() * native_height - $large.height() / 2) * -1,
            bgp = rx + "px " + ry + "px",
            px = mx - $large.width() / 2,
            py = my - $large.height() / 2;
          $large.css({
            left: px,
            top: py,
            backgroundPosition: bgp
          });
        }

      //}
    });
  };
})(jQuery);

참고: 마우스가 확대 대상으로 이동할 때 확대에서 마우스의 상대 좌표 위치를 가져와야 합니다. 여기서는 상대 좌표를 (mx, my)로 정의합니다. 상대 좌표는 (pageX - offsetLeft , pageY - offsetTop)과 같습니다.

이제 확대 개체에서 마우스의 좌표 값을 얻었습니다. 다음으로 큰 이미지의 해당 좌표를 얻어야 합니다. 여기서는 큰 이미지의 해당 좌표를 (rx, ry)로 정의합니다. 우리는 비례 관계를 사용할 수 있습니다. (rx,ry)의 값을 얻습니다.

mx / small.width(원본 이미지의 너비) = rx / Native_width(큰 이미지의 너비)

my / small.height (원본 이미지의 길이) = ry / Native_height (대형 이미지의 길이)

위의 비례 관계를 통해 큰 이미지의 좌표(rx, ry)가 (mx/small.widthnative_width, my/small.heightnative_height)와 동일하다는 것을 알 수 있습니다.

마우스휠 이벤트
앞에서는 mousemove 이벤트를 사용하여 이미지를 확대했습니다. 여기서는 마우스 휠 이벤트를 사용하여 이미지 확대 효과를 구현하겠습니다.

브라우저마다 스크롤 휠 이벤트가 다르기 때문입니다. 세 가지 주요 유형이 있습니다: onmousewheel(IE 6/7/8), mousewheel(IE9, Chrome, Safari 및 Opera) 및 DOMMouseScroll(Firefox에서만 지원됨) 이 세 가지 이벤트는 여기서 자세히 소개하지 않습니다.

브라우저 간 차이로 인해 브라우저 간 호환성을 확보하려면 위의 세 가지 휠 이벤트(onmousewheel, mousewheel 및 DOMMouseScroll)를 모니터링해야 합니다.

$(".magnify").bind('DOMMouseScroll mousewheel onmousewheel', function(e) {
});

위에서는 다양한 브라우저와 호환되는 휠 이벤트 청취 방법을 구현했습니다. 다음으로 휠이 올라갔는지 내려갔는지 판단할 때 다양한 브라우저(IE, Opera, Safari)의 호환성도 고려해야 합니다. , Firefox, Chrome), Firefox는 디테일을 사용하고 나머지 4개 카테고리는 휠델타(wheelDelta)를 사용합니다. 둘은 값이 일치하지 않을 뿐입니다. 즉, 디테일이 동일하고 휠델타는 각각 2개의 값만 취하며, 디테일은 오직 2개의 값만 취합니다. ±3이고 WheelDelta는 ±120만 사용합니다. 여기서 양수는 위쪽을 나타내고 음수는 아래쪽을 나타냅니다.

detail과 WheelDelta에는 모두 스크롤 업 또는 다운을 나타내는 두 개의 값이 있으므로, 구체적인 구현 방법은 다음과 같습니다.

$(".magnify").bind('DOMMouseScroll mousewheel onmousewheel', function(e) {

  // cross-browser wheel delta
  var e = window.event || e; // old IE support.
  var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
});

위에서는 다양한 브라우저 휠 모니터링 방법을 다루었습니다. 사용자가 휠을 스크롤하면 원본 이미지의 크기가 동적으로 수정되어야 합니다. 여기서는 크기 조정 비율을 0.3으로 정의합니다. 휠을 굴리면 원본 이미지는 0.3의 비율에 따라 크기가 조정됩니다. 구체적인 구현은 다음과 같습니다.

// Gets the image scaling height and width.
native_height += (native_height * scaling * delta);
native_width += (native_width * scaling * delta);

// Update backgroud image size.
$large.css('background-size', native_width + "px " + native_height + "px");

위에서는 돋보기 효과를 구현했습니다. 이미지 위에 마우스를 올리면 이미지의 해당 부분이 자동으로 확대됩니다. 물론 스크롤 휠을 통해 확대 비율을 조정할 수도 있습니다.

참고자료

http://tech.pro/tutorial/681/css-tutorial-the-background-position-property
http://www.sitepoint.com/html5-javascript-mouse-wheel/
http://thecodeplayer.com/walkthrough/magnifying-glass-for-images-using-jquery-and-css3

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.