jQuery plugin 要素を中央に移動させる (position center)

jQueryのouterHeight,outerWidthがイイ感じなので、こんなもの書いてみた。

単純に要素を画面中央に位置するようにtopとleftを設定するというものです。


DOMツリーに追加する前の状態でも使用可能なのがポイント。

(function($){
$.fn.extend({
  positionCenter: function() {
    var 
    $win = $(window),
    win = {
      h:$win.height(),
      w:$win.width(),
      st:$win.scrollTop(),
      sl:$win.scrollLeft()
    };
    
    return this.each(function(){
      var
      $t = $(this),
      to = {},
      posStyle =  $.css(this,'position');
      
      if(posStyle != 'absolute' && posStyle != 'fixed') {
        $t.css({ position:'absolute' });
        posStyle = $.css(this,'position');
      }
      
      function getOuterSize($x){
        to.h = $x.outerHeight();
        to.w = $x.outerWidth();
      }
      
      //!this.parentNode.tagName はIE対策
      if (!this.parentNode || !this.parentNode.tagName) {
        var $cln =$t.clone().hide().appendTo(document.body);
        getOuterSize($cln);
        $cln.remove();
      }else{
        getOuterSize($t);
      }
      
      var cPos = {
        top: Math.floor((win.h - to.h)/2),
        left: Math.floor((win.w - to.w)/2)
      }
      
      if (posStyle == 'absolute') {
        cPos.top += win.st;
        cPos.left += win.sl;
      }

      $t.css({
        top:cPos.top,
        left:cPos.left,
        margin:0
      });
    });
  }
});
})(jQuery);

こんな感じで使う。
$(function(){
 $("#hoge").click(function(){
  $(this).positionCenter();
 });
 
 $("#foo").click(function(){
  $("<p/>")
   .css({
    "border":"4px solid #333",
    "padding":"40px",
    "background-color":"#ccc"})
   .text("foo.")
   .positionCenter() //←まだDOMツリーに追加されていない状態で使用
   .appendTo(document.body);
 });
});

outerHeight,outerWidthのイイところは、該当要素のスタイル属性「visivblity」が hidden でも「display」が noneでも値を取得できるとこ。

これを改造してanimate でセンターまで移動させるってのもアリかな?

0 Comments:

Sony Style(ソニースタイル)
デル株式会社

Recent Posts