Study/jQuery
[jQuery] 마우스 호버시 이미지 확대(줌) 영역 보여주기
hyjang
2024. 11. 20. 16:24
728x90
들어가며
쇼핑몰을 보면 마우스를 호버했을 때 옆에 확대된 이미지가 뜨는것을 볼 수 있다.
마우스를 움직일때마다 확대된 이미지도 함께 움직이는데, 이 플러그인을 찾기 힘들어서 직접 제이쿼리로 구현해봤다.
script
<script>
$(function(){
/* 마우스 호버시 */
$('section article').on('mousemove', function(e){
let $zoomMark = $('.box'); // 호버시 보이는 불투명 마크 박스
let $zoomArea = $('.zoom_area'); // 줌 이미지 영역
let $zoomImg = $('.zoom_area img'); // 확대된 이미지
/* 컨테이너와 이미지 크기 가져오기 */
let $containerWidth = $(this).outerWidth();
let $containerHeight = $(this).outerHeight();
let markWidth = $zoomMark.outerWidth();
let markHeight = $zoomMark.outerHeight();
/* 마우스 위치 계산 */
let x = e.pageX - $(this).offset().left - markWidth/2;
let y = e.pageY - $(this).offset().top - markHeight/2;
/* 확대 마크 위치 제한 */
x = Math.max(0, Math.min(x, $containerWidth - markWidth));
y = Math.max(0, Math.min(y, $containerHeight - markHeight));
/* 줌 이미지의 이동 비율 계산 */
let $zoomImgX = x * ($zoomImg.outerWidth()/$containerWidth);
let $zoomImgY = y * ($zoomImg.outerHeight()/$containerHeight);
/* 줌 영역 박스 크기 지정 */
$zoomArea.css({'width': $zoomImg.outerWidth() / ($containerWidth/markWidth), 'height':$zoomImg.outerHeight() / ($containerHeight/markHeight)});
/* 줌 이미지 이동 계산 */
$zoomMark.css({'left': x, 'top': y});
$zoomImg.css({'top': - $zoomImgY, 'left': - $zoomImgX});
/* 줌 영역 표시 */
$zoomMark.show();
$('.zoom_area').show();
})
/* 마우스 이탈시 */
$('section article').on('mouseleave', function(){
$('.zoom_area').hide();
$('.box').hide();
})
});
</script>
마우스 호버시 보이는 줌 영역 박스는 기존 이미지와 확대 이미지의 비례하여 넓이와 높이값이 정해지도록 했다.
이렇게 진행하면 이미지의 크기가 바뀌어도 저절로 영역 크기를 잡아줄 수 있다.
만약 줌 영역 박스를 직접 조절하고 싶다면 /* 줌 영역 박스 크기 지정 */ 부분을 삭제하면 된다.
CSS
<style>
*{margin:0; padding: 0;}
img{font-size: 0;}
section{ position: relative; }
article{ width:500px; height:500px; border:1px solid #333; position:absolute; left:700px;}
article img{width:100%; height:100%;}
section article .box{display: none; position:absolute; width:200px; height:200px; background:rgba(255,255,255,0.4); border:1px #333 solid; box-sizing: border-box; }
.zoom_area{display: none; position:relative; left:1200px; overflow: hidden; width:400px; height:400px; border:lightblue 2px solid; box-sizing: border-box; }
.zoom_area img { position:absolute; }
</style>
HTML
<body>
<section>
<article>
<img src="image1.jpg" alt="">
<div class="box"></div>
</article>
<div class="zoom_area"><img src="image1.jpg" alt=""></div>
</section>
</body>