简体   繁体   中英

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM