본문 바로가기
#Dev

마우스 hover 이미지 확대 & 미리보기

by 알쓸신잡스 2019. 12. 12.

이미지에 마우스 포인터 호버 됬을떄 이미지를 확대된 크기로 미리보기를 하고 싶었다.

 

$(document).ready(function() {
						  
			var xOffset = 250;
			var yOffset = 330;

			$(document).on("mouseover",".imgItem",function(e){ //마우스 오버될때
				 
				$("body").append("<div id='preview'><img src='"+ $(this).attr("src") +"' width='300px'/></div>"); //보여줄 이미지를 선언                      
				$("#preview")
					.css("top",(e.pageY - xOffset) + "px")
					.css("left",(e.pageX - yOffset) + "px")
					.fadeIn("fast"); 
			});
			 
			$(document).on("mousemove",".imgItem",function(e){ //마우스 이동시
				$("#preview")
					.css("top",(e.pageY - xOffset) + "px")
					.css("left",(e.pageX - yOffset) + "px");
			});
			 
			$(document).on("mouseout",".imgItem",function(){ //마우스 아웃시
				$("#preview").remove();
			});
						  
		});

 

 

처음엔 구글링해서 위와 같이 구현했지만...

테이블에서 제일 아래행의 미리보기가 제대로 되지 않고 동작이 부자연스러웠다.

 

 

 

그래서 제이쿼리 UI 에서 Tooltip을 사용했다.

https://jqueryui.com/tooltip/

 

Tooltip | jQuery UI

Tooltip Customizable, themeable tooltips, replacing native tooltips. Hover the links above or use the tab key to cycle the focus on each element. view source 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

jqueryui.com

 

<img src="www.example.com/example.jpg" class="imgItem" data-tooltip="<div style='position:relative;'><img src='www.example.com/example.jpg'/>">

 

$(document).tooltip({
	items: 'img[data-tooltip]',
	tooltipClass: 'preview-ui-tooltip',
	open: function(event, ui) {
		$(this).tooltip('option', 'position', {
			my: "right center",
			at: "left center",
			collision: "flipfit flipfit"
		});
	},
	track: false,
	content: function() {
		var $this = $(this);
		var contents = $($this.data('tooltip'));
		var width = 300;
		if($this.width() > $this.height()) width = 500;
		var height = width * ($this.height() / $this.width());
		if(height <= 0 || isNaN(height)) contents.css({'max-height': '450px'});
		else contents.css({'height': height + 'px'});
		contents.css({'width': width + 'px'});

		return contents;
	}
});

 

 

플러그인 사용하는게 더 간편하고 기능도 좋다.