jquery要素相対位置決めコード

2076 ワード

 
  
/**
*jQuery rposition
*fix:
*rel:
*options:{},align: ;vlign: ;xleft: ;xleft: ;adjust: ;rwindow: (align&vlign center );
*/
(function(win,$){
win.rposition=function(fix,rel,options){
var rectLeft,rectTop,rectH=fix.outerHeight(),rectW=fix.outerWidth(),wh=$(window).height(),ww=$(window).width(),
sT=$(document).scrollTop(),sL=$(document).scrollLeft(),
defaults={
align:"left",
vlign:"top",
xleft:0,
xtop:0,
adjust:true,
rwindow:false
},
options = $.extend(defaults, options);
var rectRel={
l:$(rel).offset().left,
t:$(rel).offset().top,
w:$(rel).outerWidth(),
h:$(rel).outerHeight()
};
switch(options.align){
case "left":
rectLeft=rectRel.l;break;
case "right":
rectLeft=rectRel.l+rectRel.w;break;
case "center":
rectLeft=rectRel.l+rectRel.w/2;break;
case "rleft":
rectLeft=rectRel.l-rectW;break;
default:
rectLeft=rectRel.l;
};
switch(options.vlign){
case "top":
rectTop=rectRel.t;break;
case "center":
rectTop=rectRel.t+rectRel.h/2;break;
case "vbottom":
rectTop=rectRel.t-rectH; break;
case "bottom":
default:
rectTop=rectRel.t+rectRel.h;
};
if(options.rwindow){
if(options.align=="center")rectLeft=(ww-rectW)/2+sL;
if(options.vlign=="center")rectTop=(wh-rectH)/2+sT;
};
if(options.adjust){
if(rectLeft+rectW>ww+sL){rectLeft-=(rectLeft+rectW)-(ww+sL)}
if(rectTop+rectH>wh+sT){rectTop=rectRel.t-rectH;}
};
$(fix).css({"left":rectLeft+options.xleft,"top":rectTop+options.xtop});
}
})(window,jQuery)