scroll頁面對齊

by xcatx

HTML

<div id="area">
    <div id="header">表頭</div>
    <div id="menu">選單</div>
    <div id="content">
        <div id="map">map</div>
        <div id="main">main</div>
        <div id="side">side</div>
    </div>
    <div id="footer">表尾</div>
</div>

CSS

div {
    background:url(http://i.imgur.com/1phcx2K.png);
}
#area {
    width:500px;
    margin:auto;
    position:relative;
}
#header {
    position:relative;
    height:100px;
    background-color:#9CC;
}
#menu {
    position:relative;
    height:50px;
    background-color:#CC9;
    z-index:2;
}
#content {
    position:relative;
    overflow:hidden;
}
#map {
   height:200px;
}
#main {
    position:relative;
    float:left;
    width:400px;
    height:900px;
    background-color:#3CC;
    border-bottom:5px solid #039;
}
#side {
    position:relative;
    float:left;
    width:100px;
    height:500px;
    background-color:#FC9;
    border-bottom:5px solid #930;
}
#footer {
    position:relative;
    height:150px;
    background-color:#9CC;
}

JavaScript

var $win = $(window).scroll(function () {
    var $menu = $('#menu'),
        $header_h = $('#header').outerHeight(),
        $side = $('#side'),
        $main = $('#main');

    //menu
    if ($win.scrollTop() >= $header_h) {
        $menu.css({
            'top': $win.scrollTop() - $header_h
        });
    } else {
        $menu.css({
            'top': 0
        });
    }

    //content
    //判斷main跟side誰比較短
    if ($side.outerHeight() < $main.outerHeight()) {
        var $the = $side,
            $the2 = $main;
    } else {
        var $the = $main,
            $the2 = $side;
    }
    var $the_h = $the.outerHeight(),
	    $the2_h = $the2.outerHeight(),
        $h_h = $header_h + $menu.outerHeight()+$the2.position().top,
        $h_t = $header_h+$the2.position().top;

    //判斷固定區有沒有比畫面短
    if ($the_h + $menu.outerHeight() < $win.height()) {
        //靠上對齊
        if ($win.scrollTop() > $h_t + $the2_h - $the_h ) {
            $the.css('top',$the2_h - $the_h);
        } else if ($win.scrollTop() > $h_t) {
            $the.css('top', $win.scrollTop() - $h_t);
        } else {
            $the.css('top', 0);
        }
    } else {
        //靠下對齊
        if ($win.scrollTop() >$h_h + $the2_h - $win.height()) {
            $the.css('top',$the2_h - $the_h);
        } else if ($win.scrollTop() > $h_h + $the_h - $(window).height()) {
            $the.css('top', $win.scrollTop() - ($h_h + $the_h - $(window).height()));
        } else {
            $the.css('top', 0);
        }
    }
$side.text($header_h+$the2.position().top+','+$win.scrollTop())

});