728x90

 

<style>
body { margin: 0; }
.fixed { position: fixed; top:0; left:0; }
</style>
<script src="http://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
$(function() {
	$.fn.Scrolling = function(obj, tar) {
		var _this = this;
		$(window).scroll(function(e) {
			var end = obj + tar;
			$(window).scrollTop() >= obj ? _this.addClass("fixed") : _this.removeClass("fixed");
			if($(window).scrollTop() >= end) _this.removeClass("fixed");
		});
	};

	$("#test1").Scrolling($("#test1").offset().top, ($(".aa").height() - $("#test1").height()));
	$("#test2").Scrolling($("#test2").offset().top, ($(".bb").height() - $("#test2").height()));
});
</script>
<div style="background: red; width: 200px; height: 440px;">test</div>
<div class="aa" style="background: #ccc; width: 100%; height: 700px;">
	<div id="test1" style="border: 1px solid #000; width: 90%; height: 200px; background: #fff;">asdfasf</div>
</div>
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
<div class="bb" style="background: #ccc; width: 100%; height: 700px;">
	<div id="test2" style="border: 1px solid #000; width: 90%; height: 100px; background: #fff;">asdfasf</div>
</div>
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
... 생략 ...
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />
Lorem ipsum etc etc<br />

쇼핑몰 같은 데에서 특정 위치까지 스크롤을 하면 메뉴가 고정되었다가 또 특정 위치를 벗어나면 고정이 해제되는...

말로 설명하는 것보다 예제를 보시는 게 더 나을 것 같네요.

사용 방법은 아래와 같습니다.

 

$("고정시킬 div").Scrolling("고정시킬 div의 시작 위치", "어디까지 고정할지");

$("#test1").Scrolling($("#test1").offset().top, ($(".aa").height() - $("#test1").height()));

[Sample]

댓글 0