jQuery > Custom Plugin

by s_hiroshi

HTML

<div id="outer">
    <div id="inner">Hello World</div>
</div>
<div id="alone">aaa</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() {
        // 自身のサイズ
        var width = $(this).width();
        var height = $(this).height();
        var parentWidth;
        var parentHeight;
        var parentCssPos
        // 要素親のサイズ
        if ($(this).parent().get(0) == $('body').get(0)) {
            parentWidth = $(window).width();
            parentHeight = $(window).height();
        } else {
            parentWidth = $(this).parent().width();
            parentHeight = $(this).parent().height();
            parentCssPos = $(this).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().css('backgroundColor', 'yellow');
    $('#alone').setCenter();

});