利用jq让你的div居中的好方法分享
very short version:
. 代码如下:
$('#mydiv').css({top:'50%',left:'50%',margin:'-'+($('#mydiv').height() / 2)+'px 0 0 -'+($('#mydiv').width() / 2)+'px'});
short version:
. 代码如下:
(function($){
$.fn.extend({
center: function () {
return this.each(function() {
var top = ($(window).height() - $(this).outerheight()) / 2;
var left = ($(window).width() - $(this).outerwidth()) / 2;
$(this).css({position:'absolute', margin:0, top: (top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});
});
}
});
})(jquery);
activated by this code :
$('#maindiv').center();
plugin version
. 代码如下:
(function($){
$.fn.extend({
center: function (options) {
var options = $.extend({ // default values
inside:window, // element, center into window
transition: 0, // millisecond, transition time
minx:0, // pixel, minimum left element value
miny:0, // pixel, minimum top element value
withscrolling:true, // booleen, take care of the scrollbar (scrolltop)
vertical:true, // booleen, center vertical
horizontal:true // booleen, center horizontal
}, options);
return this.each(function() {
var props = {position:'absolute'};
if (options.vertical) {
var top = ($(options.inside).height() - $(this).outerheight()) / 2;
if (options.withscrolling) top += $(options.inside).scrolltop() || 0;
top = (top > options.miny ? top : options.miny);
$.extend(props, {top: top+'px'});
}
if (options.horizontal) {
var left = ($(options.inside).width() - $(this).outerwidth()) / 2;
if (options.withscrolling) left += $(options.inside).scrollleft() || 0;
left = (left > options.minx ? left : options.minx);
$.extend(props, {left: left+'px'});
}
if (options.transition > 0) $(this).animate(props, options.transition);
else $(this).css(props);
return $(this);
&nnbsp; });
}
});
})(jquery);
activated by this code :
. 代码如下:
$(document).ready(function(){
$('#maindiv').center();
$(window).bind('resize', function() {
$('#maindiv').center({transition:300});
});
);
上一篇: jquery使用淘宝接口跨域查询手机号码归属地实例
下一篇: 文本框只能选择数据到文本框禁止手动输入