jQuery > setCenter .2

by s_hiroshi

HTML

<div id="outer">
    <div id="inner">Hello World</div>
</div>

CSS

div#outer {
    width: 400px;
    height: 200px;
    border: 10px solid #666;
}
div#inner {
    width: 100px;
    height: 100px;
    border: 5px solid #ccc;
}
div#alone {
    width: 100px;
    height: 100px;
    border: 5px solid green;
}

JavaScript

jQuery(function($) {
    jQuery.fn.setCenter = function(value) {
        // 基点となる要素の設定
        var parent = $(value);
        if (!parent instanceof jQuery) {
            parent = $(parent);
        }
        console.log(parent);
        // 自身のサイズ
        var width = $(this).width();
        var height = $(this).height();
        // 親要素のサイズ
        var parentWidth = parent.width();
        var parentHeight = parent.height();
        var parentCssPos;
        // 要素親のポジション        
        parentCssPos = parent.css('position');
        if ((parentCssPos != 'absolute') && (parentCssPos != 'relative')) {
            $(this).parent().css({
                position: 'relative'
            });
        }
        // オフセット
        var offsetX = (parentWidth - width) / 2;
        var offsetY = (parentHeight - height) / 2;
        // 中央は位置
        $(this).css({
            position: 'absolute',
            top: offsetY,
            left: offsetX
        });
        return $(this);
    };

    $('#inner').setCenter('#outer').css('backgroundColor', 'yellow');

});