jQuery 实现滚动页面固定 div 元素

和大家分享一下我写的一个滚动页面且固定 div 元素的例子,现在很多网站都用到了这样的效果。

CSS Code:

.fixed, #scrollarea {
	background-color: #F0F0F0;
	height: 210px;
	margin-bottom: 10px;
	width: 280px;
}
#scrollarea {
	height: 630px;
}
.move {
	background-color: #F00;
	color: #FFF;
	height: 210px;
	position: absolute;
	width: 280px;
}
.scroll {
	background-color: #00F;
	position: fixed;
	top: 0;
}

HTML Code:

<div class="fixed"> 1 </div>
<div class="fixed"> 2 </div>
<div id="scrollarea">
  <div class="move" id="scroll">我现在是红色,现在还没固定。</div>
</div>
<div class="fixed"> 3 </div>
<div class="fixed"> 4 </div>
<div class="fixed"> 5 </div>

jQuery Code:

$(function ($) {
    var loaded = true;
    var scroll_height = $("#scrollarea").height() - $("#scroll").height();
    var start_top = $("#scroll").offset().top;
    var stop_top = $("#scrollarea").offset().top + scroll_height;
    scrollfixed();

    function scrollfixed() {
        var scrolltop = $(window).scrollTop();
        var start_cha = start_top - scrolltop;
        var stop_cha = stop_top - scrolltop;
        if (loaded && start_cha <= 0 && start_cha >= -scroll_height) {
            $("#scroll").removeAttr("style");
            $("#scroll").addClass("scroll");
            $("#scroll").html("我现在是蓝色,现在已经固定。");
            loaded = false;
        }
        if (!loaded && stop_cha <= 0) {
            $("#scroll").removeClass("scroll");
            $("#scroll").css('top', stop_top);
            loaded = true;
        }
        if (!loaded && start_cha > 0) {
            $("#scroll").removeClass("scroll");
            $("#scroll").html("我现在是红色,现在还没固定。");
            loaded = true;
        }
    }
    $(window).scroll(scrollfixed);
});

查看 Demo

发表评论

电子邮件地址不会被公开。 必填项已用*标注