1

我有这个 jQuery 函数:

    $(window).resize(function(){
  $('#modal').css({
    left: ($(window).width() - $('#modal').outerWidth())/2,
    top: ($(window).height() - $('#modal').outerHeight())/2
  });
});

这就是我需要做的:“在窗口调整大小时将 div 放在屏幕的中心”。唯一的问题是,当我将窗口缩小到足够(400-500 像素)或从低分辨率设备(手机)访问网页时,标题会超出边界,您再也看不到它了。

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

4

3 回答 3

1

您可以添加一个小测试:

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

  $('#modal').css({
    left: ($(window).width() - $('#modal').outerWidth())/2,
    top: topPos > 0 ? topPos : 0
  });
});
于 2012-11-29T09:41:51.107 回答
1

此功能可能会有所帮助:

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 );
    }
}
于 2012-11-29T09:43:22.363 回答
0

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

   #modal {
      width: 500px;
   }

    @media only screen and (max-width: 500px) {
      #modal { 
          width: 100%;
      }
    }
于 2012-11-29T09:44:18.373 回答