jQuery自动div定位在屏幕中央

时间:2012-11-29 09:36:51

标签: javascript jquery html

我有这个jQuery函数:

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

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

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

3 个答案:

答案 0 :(得分:1)

您可以添加一个小测试:

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

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

答案 1 :(得分: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 );
    }
}

答案 2 :(得分:0)

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

   #modal {
      width: 500px;
   }

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