欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

利用jq让你的div居中的好方法分享

程序员文章站 2022-06-05 09:03:59
very short version: . 代码如下: $('#mydiv').css({top:'50%',left:'50%...

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});
    });
);