Javascript jQuery在屏幕中央自动定位div

Javascript jQuery在屏幕中央自动定位div,javascript,jquery,html,Javascript,Jquery,Html,我有这个jQuery函数: $(window).resize(function(){ $('#modal').css({ left: ($(window).width() - $('#modal').outerWidth())/2, top: ($(window).height() - $('#modal').outerHeight())/2 }); }); 这就是我需要的:“将div放置在窗口调整大小时屏幕的中心”。唯一的问题是,当我将窗口缩小到足够大(400

我有这个jQuery函数:

    $(window).resize(function(){
  $('#modal').css({
    left: ($(window).width() - $('#modal').outerWidth())/2,
    top: ($(window).height() - $('#modal').outerHeight())/2
  });
});
这就是我需要的:“将div放置在窗口调整大小时屏幕的中心”。唯一的问题是,当我将窗口缩小到足够大(400-500px)或从低分辨率设备(移动电话)访问网页时,标题会超出上方的边界,你再也看不到它了


为什么会发生这种情况以及我如何避免这种情况?

您只需添加一个小测试:

$(window).resize(function(){
  var topPos = ($(window).height() - $('#modal').outerHeight())/2;

  $('#modal').css({
    left: ($(window).width() - $('#modal').outerWidth())/2,
    top: topPos > 0 ? topPos : 0
  });
});

此功能可能有助于:

function setToCenterOfParent( obj, parentObj ) {
    var height = $( obj ).height();
    var width = $( obj ).width();
    if ( parentObj == window ) {
        $( obj ).css( 'top', ( $( parentObj ).height() / 2 ) - ( height / 2 ) );
        $( obj ).css( 'left', ( $( parentObj ).width() / 2 ) - ( width / 2 ) );
    }
    else {
        $( obj ).css( 'top', ( $( parentObj ).height() / 2 ) - ( height / 2 ) + $( parentObj ).position().top );
        $( obj ).css( 'left', ( $( parentObj ).width() / 2 ) - ( width / 2 ) + $( parentObj ).position().left );
    }
}

如果窗口小于模态,则会进入负值。重要的是思考在这种情况下应该发生什么。我通常停止定位窗口,使模式覆盖整个窗口:使用CSS媒体查询,我从定义的px值更改模式大小,以匹配屏幕大小相对值

   #modal {
      width: 500px;
   }

    @media only screen and (max-width: 500px) {
      #modal { 
          width: 100%;
      }
    }

如何使用此功能?