Skip to content

Instantly share code, notes, and snippets.

@s-hiroshi
Last active September 30, 2015 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s-hiroshi/12ef444318ed62b9967c to your computer and use it in GitHub Desktop.
Save s-hiroshi/12ef444318ed62b9967c to your computer and use it in GitHub Desktop.
/**
* 中央配置用オフセット取得
*
* target要素をparent要素の中央へ配置するために
* CSSのtop, leftプロパティへ設定すべき値を取得します。
*
* @method getOffset
* @public
* @param {jQuery} target 中央配置するjQueryオブジェクトです。
* @param {jQuery} parent 親のjQueryオブジェクトです。
* @return {Object} CSSのtop, leftプロパティの値を返します。
*/
function getOffset( target, parent ) {
var width, height, parentWidth, parentHeight;
target = (target instanceof jQuery) ? target : $( target );
parent = parent || $( 'body' );
parent = (parent instanceof jQuery) ? parent : $( parent );
/* ターゲットのサイズ取得 */
width = target.width();
height = target.height();
/* 要素親のサイズ取得 */
parentWidth = parent.width();
parentHeight = parent.height();
/* オフセット */
return {
"x": (parentWidth - width ) / 2,
"y": (parentHeight - height) / 2
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment