开发者

JQuery function not working as expected

I've written a little function to position a logo midway between the left hand side of the browser window and the (centered) navigation menu. The menu items are populated from a database, with the first item given the id item0.

function positionLogo(){
    var $menuleft=0;
    var $element=document.getElementById('item0');
    if ($element.offsetParent) {
        do {
            $menuleft+=$element.offsetLeft;
        } while ($element=$element.offsetParent);
    }
    var $logoleft=($menuleft/2)-130; // As logo is 260px wide
    if ($logoleft<0) {
        $logoleft=0;
    }
    $('#logo').css('left',$logoleft);
}

$(document).ready(function(){
    positionLogo();
});

$(window).resize(function(){
    positionLogo();
});

This works fine when the window is resized, but when it first runs when the page is loaded, the position it sets is about 20px too far right (ie $logoleft is 20 more than it should be). As soon as the page is resized it jumps into the correct position.

Haven't got it live anywhere at the moment but does anyone have any ideas? Thanks!开发者_如何转开发


Replace this:

$(document).ready(function(){
    positionLogo();
});

$(window).resize(function(){
    positionLogo();
});

With this:

$(window).bind('load resize', positionLogo);

You need the layout and all sizes to finish up (images loading, etc), so you want the window.load method instead of document.ready. Combine that with bind() taking space separated events and you can get it down into a simple one-line handler like that. One other note, no need to wrap only a function in function() { }, just put the function name like I have above :)


Have you tried handling window.onload? This will fire when the page is completely loaded, rather then when the DOM is ready (like $(document).ready)


I wasn't able to repeat the phenomenon. There is some bug in IE that has to do with offsetParent, that might have something to do with it depending on how you have positioned the elements. You can use the offset method in jQuery to get around the browser incompatiblities there.

For some reason it seems to work even in Firefox without specifying a unit for the left style, but it really should have one.

function positionLogo(){
   var menuleft = $('#item0').offset().left;
   var logoleft = Math.max(0, (menuleft / 2) - 130); // As logo is 260px wide
   $('#logo').css('left', logoleft + 'px');
}

or simply:

function positionLogo(){
   $('#logo').css('left', Math.max(0, ($('#item0').offset().left / 2) - 130) + 'px');
}


If resizing the window is working then maybe you should try triggering the function with a resize:

so replace:

$(document).ready(function(){
    positionLogo();
});

with:

$(document).ready(function(){
    $(window).resize();
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜