Archive / Javascript / 스크롤 따라 움직이는 레이어

페이지 스크롤에 따라서 부드럽게 움직이는 레이어를 만드는 스크립트이다. 쇼핑몰이나 웹사이트에서 사이트 오른쪽에 스크롤을 따라다니는 탑버튼이나 퀵메뉴, 윙배너 구현에 사용할 수 있다.

IE6, IE7, IE8, FF3.6, Opera10.50, Safari4에서 테스트 되었다. IE의 쿽스모드와 표준모드 양쪽에서 작동한다.

코드

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=euc-kr">
<title>SmoothMovingLayer Demo</title>
<script type="text/javascript">
//<![CDATA[
function initMoving(target, position, topLimit, btmLimit) {
	if (!target)
		return false;

	var obj = target;
	obj.initTop = position;
	obj.topLimit = topLimit;
	obj.bottomLimit = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight) - btmLimit - obj.offsetHeight;

	obj.style.position = "absolute";
	obj.top = obj.initTop;
	obj.left = obj.initLeft;

	if (typeof(window.pageYOffset) == "number") {	//WebKit
		obj.getTop = function() {
			return window.pageYOffset;
		}
	} else if (typeof(document.documentElement.scrollTop) == "number") {
		obj.getTop = function() {
			return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
		}
	} else {
		obj.getTop = function() {
			return 0;
		}
	}

	if (self.innerHeight) {	//WebKit
		obj.getHeight = function() {
			return self.innerHeight;
		}
	} else if(document.documentElement.clientHeight) {
		obj.getHeight = function() {
			return document.documentElement.clientHeight;
		}
	} else {
		obj.getHeight = function() {
			return 500;
		}
	}

	obj.move = setInterval(function() {
		if (obj.initTop > 0) {
			pos = obj.getTop() + obj.initTop;
		} else {
			pos = obj.getTop() + obj.getHeight() + obj.initTop;
			//pos = obj.getTop() + obj.getHeight() / 2 - 15;
		}

		if (pos > obj.bottomLimit)
			pos = obj.bottomLimit;
		if (pos < obj.topLimit)
			pos = obj.topLimit;

		interval = obj.top - pos;
		obj.top = obj.top - interval / 3;
		obj.style.top = obj.top + "px";
	}, 30)
}
//]]>
</script>
<style type="text/css">
body {
	margin: 0;
}
#head {
	width: 800px;
	height: 3000px;
	background: #eee;
}
#gotop {
	position: absolute;
	left: 810px;
	top: 50px;
	background: #ddd;
	width: 100px;
	height: 1000px;
}
</style>
</head>
<body>
<div id="head">
	웹사이트 헤더
</div>
<div id="gotop">
	<a href="#head" title="상단으로">위로</a>
</div>
<script type="text/javascript">initMoving(document.getElementById("gotop"), 50, 50, 50);</script>
</body>
</html>

사용법

initMoving(움직일 대상, 스크롤위치, 상단 한계, 하단 한계);

움직일 대상은 HTML 오브젝트로 지정한다. 스크롤위치는 오브젝트가 스크롤을 따라서 고정될 브라우저 창 위 경계로부터의 위치이다. 상단 한계는 웹 페이지에서 오브젝트가 올라갈 수 있는 한계 위치이다. 하단 한계는 웹 페이지에서 오브젝트가 내려갈 수 있는 한계 위치이다.

스크롤위치(position)값이 양수이면 브라우저의 상단으로 부터의 거리, 음수이면 하단으로 부터의 거리로 계산이 된다. 상단 위치는 디자인 상의 이유로 오브젝트의 상단 한계를 정할 때 유용하다. 하단 한계는 브라우저 창이 작을 때 오브젝트가 한없이 내려가는 현상을 방지해 준다.

페이지에 이미지가 많아서 오브젝트가 페이지 끝까지 잘 내려가지 않을 경우 initMoving을 load 이벤트에서 적용하면 된다.

참고링크

W3C DOM Compatibility - CSS Object Model View

Page last modified on March 13, 2010, at 11:45 PM