当我将绝对位置div“top”设置为700px时,jquery offset()。top返回0

时间:2011-12-10 10:58:43

标签: jquery html css

我想要在某个位置显示菜单栏 页面,无论浏览器的大小是多少 并且当窗口调整大小时,其位置将更新

当页面滚动到某个点时,菜单将保持不变

这就是我所做的:

*调整窗口大小时会出现问题,导航的offsetTop已更新 但它返回0,我不知道为什么,也许offset()不能被调用两次?

谢谢!!!!!

HTML:

<div id="nav">

                <ul id="nav_list">
                    <li>
                    ABOUT
                    </li>
                    <li>
                    WORK
                    </li>
                    <li>
                    CONTACT
                    </li>
                    <li>
                    BLOG
                    </li>
                </ul>

            </div>

css:

#nav{
position:absolute;
    width:100%;
    height:50px;
    line-height:50px;
    background:#0C6;
    display:block;
    z-index:104;
}

#nav_list{
    margin:auto;
    padding:0;
    width:380px;
    font-family:FoundryJournal-Book;
    font-size:25px;
    color:#C36;
    list-style:none;
}
#nav_list li{
    margin-right:10px;
    display:inline;
}

jquery:

var scrollTop;
var nav_offsetTop;
var window_height=$(window).height();
var window_height_resize;

// set the nav position !
if(parseInt(window_height)>=700){
        $("#nav").css({top:parseInt(window_height)-5});
        nav_offsetTop=$("#nav").offset().top;
    }


// when window resize

// declare resize delay function
    var resize_delay = (function () {
    var timers = {};
    return function (callback, ms, uniqueId) {
    if (!uniqueId) {
      uniqueId = "Don't call this twice";
    }
    if (timers[uniqueId]) {
      clearTimeout (timers[uniqueId]);
    }
    timers[uniqueId] = setTimeout(callback, ms);
    };
    })();

$(window).resize(function(){
        resize_delay(function(){
            window_height_resize=$(window).height();
            /* all things needed updated after window resizing */

            // nav re-position
            if(window_height_resize>=780){
               $("#nav").fadeOut(200,function(){
                            // update nav's position
                $(this).css({top:parseInt(window_height_resize)-5});

                            // update nav_offsetTop after resizing
                nav_offsetTop=$(this).offset().top;
                alert(nav_offsetTop)  // return 0 ?!!!!
                $(this).fadeIn(250);
               });
            }
        },20,"window_resize");
 });


//scroll
$(window).scroll(function(){
        scrollTop=$(this).scrollTop();

        // nav stay fixed
        if(scrollTop>=nav_offsetTop){
            $("#nav").css({position:"fixed",top:"0px"});
        }else{
            $("#nav").css({position:"absolute",top:nav_offsetTop});
        }
 });

小提琴:http://jsfiddle.net/U2hX3/1/

0 个答案:

没有答案