본문 바로가기
IT 이야기/JQuery.Script

[2011.05.21] 스크롤 따라 움직이는 레이어

by Mr. 김반장 2011. 5. 21.
<!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=utf-8">
<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(움직일 대상, 스크롤위치, 상단 한계, 하단 한계);

[출처 - "신현석'님의 블로그]

댓글