Web 프로그래밍/Javascript & jQuery

[Javascript & jQuery] 이미지 크기에 맞게 팝업띄우기

베로베로스 2016. 11. 2. 12:27



이미지 클릭시 팝업으로 원본을 보여주는 스크립트입니다.

IE6,7의 경우 스크롤바가 있고 없고에 따라 창크기가 달라져 이미지 크기에 딱맞게 띄울 경우 원치 않는 스크롤이 생길 수 있습니다.

그래서 팝업 띄울때 스크롤바 자리는 일단 확보해줍니다.

(scrollbars=yes) 파폭이나 크롬에서는 이렇게 해줘도 창크기를 넘지 않는 이상은 스크롤바가 보이지 않네요.

스크롤바가 생겨도 내용이 표시되는 자리가 좁아지지는 않죠.

헌데 IE는 좀 달라서 내용 보여질 자리가 좁아져 버리기때문에 미리 확보합니다.

보통 크기의 이미지를 띄울때 IE에서 스크롤바 자리가 있다보니 버젼 체크해서 그 크기만큼 가로를 좀 늘려줍니다.

최대 크기(screen 크기 기준)를 초과할 경우에는 어쩔수 없이 이미지보다 작은 창을 띄우기 때문에 그로 인한 스크롤바 자리를 확보해줍니다.


[Javascript 소스]

<script type="text/javascript">
var imgCommonPreview = new Image();
function viewPic(filepath) {
	if(filepath == "") {
		alert('등록된 이미지가 없습니다.');
		return;
	}

	imgCommonPreview.src = filepath;
	setTimeout("createPreviewWin(imgCommonPreview)", 100);
}

function createPreviewWin(imgCommonPreview) {
	if(!imgCommonPreview.complete) {
		setTimeout("createPreviewWin(imgCommonPreview)", 100);
		return;
	}

	var scrollsize = 17;
	var swidth = screen.width - 10;
	var sheight = screen.height - 90;
	var wsize = imgCommonPreview.width
	var hsize = imgCommonPreview.height;

	if(wsize < 50) wsize = 50;		// 가로 최소 크기
	if(hsize < 50) hsize = 50;		// 세로 최소 크기
	if(wsize > swidth) wsize = swidth;	// 가로 최대 크기
	if(hsize > sheight) hsize = sheight;	// 세로 최대 크기

	// 세로가 최대크기를 초과한경우 세로스크롤바 자리 확보
	if((wsize < swidth-scrollsize) && hsize >= sheight) wsize += scrollsize;

	// 가로가 최대크기를 초과한경우 가로스크롤바 자리 확보
	if((hsize < sheight-scrollsize) && wsize >= swidth) hsize += scrollsize;

	// IE 6,7 전용 : 가로세로 크기가 보통일때 세로 스크롤바 자리 확보
	if((wsize < swidth-scrollsize) && hsize < sheight 
		&& (navigator.userAgent.indexOf("MSIE 6.0") > -1
		|| navigator.userAgent.indexOf("MSIE 7.0") > -1))wsize += scrollsize; 

	// 듀얼 모니터에서 팝업 가운데 정렬하기
	var mtWidth = document.body.clientWidth;	// 현재 브라우저가 있는 모니터의 화면 폭 사이즈
	var mtHeight = document.body.clientHeight;	// 현재 브라우저가 있는 모니터의 화면 높이 사이즈
	var scX = window.screenLeft;			// 현재 브라우저의 x 좌표(모니터 두 대를 합한 총 위치 기준)
	var scY = window.screenTop;			// 현재 브라우저의 y 좌표(모니터 두 대를 합한 총 위치 기준)
	var popX = scX + (mtWidth - wsize) / 2 - 50;	// 팝업 창을 띄울 x 위치 지정(모니터 두 대를 합한 총 위치 기준)
	var popY = scY + (mtHeight - hsize) / 2 - 50;	// 팝업 창을 띄울 y 위치 지정(모니터 두 대를 합한 총 위치 기준)

	// window.open('주소', '이름(공란가능)', '속성');
	imageWin = window.open("", "", "top=" + popY
				+ ",left=" + popX
				+ ",width=" + wsize
				+ ",height=" + hsize
				+",scrollbars=yes,resizable=yes,status=no");
	imageWin.document.write("<html><title>Preview</title><body style='margin:0;cursor:pointer;' title='Close' onclick='window.close()'>");
	imageWin.document.write("<img src='" + imgCommonPreview.src + "'>");
	imageWin.document.write("</body></html>");
}
</script>


[html 소스]

<a style="cursor:pointer;" onclick="javascript:viewPic('http://www.test.com/images/sample.png')">이미지 보기</a>




[Reference]


http://fbb.kro.kr/120149286711