开发者

How to center a relatively positioned element with jquery?

I am trying to make a function which returns "what the left value should be to center the current element". This 开发者_运维问答allows me to animate to the center (and back) or to simply center an item.

I am having trouble with the relative positioning part though. What did I miss?

Thanks!


jQuery.fn.centerHorizontalOffset = function () {
    var position = $(this).css("position");
    if (position == "relative"){
        return (($(window).width() - $(this).width()) / 2) - $(this).parent().offset().left;
    } else if (position == "absolute"){
        return ($(window).width() - $(this).width()) / 2;
    }
    return ($(window).width() - $(this).width()) / 2;
}
jQuery.fn.centerHorizontalDistance = function () {
    return $(this).centerHorizontalOffset()-$(this).position().left;
}
$('#myDiv').css('left', $('#myDiv').centerHorizontalDistance());


I would look into using jQuery UI's new "Position" plugin: http://jqueryui.com/demos/position/ - it's great at doing exactly what you're after.

...not a direct answer to your question I know, but this has saved me a ton of time, and why re-invent the wheel? =). Good luck!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜