jQuery .css()不影响div

时间:2013-04-01 20:37:43

标签: jquery html5 css3

对于我正在处理的应用,我最近实现了一个吸收用户输入的叠加层。当然,这只是我的目标之一 - 我还需要将居住在这个叠加层内的popover居中。

到目前为止,这是我的设置:

标记

<!-- snip extra HTML -->

<div id='some-overlay' class='input-eater hidden'>
  <div id='some-prompt' class='overlay dialogue'>
    This is a message that should be hidden.<br /><br />
    <a href='javascript: $('#some-overlay').fadeOut();'>Click Here To Close</a>
  </div>
</div>

<!-- ...SNIP... -->

...后台页面上的某些操作会导致#some-overlay淡入,从而遮挡页面,直到关闭操作发生。这是违规的JavaScript:

<!-- ...Continued from the markup above... -->
<script>
var $button = $('.some-element'),
    $overlay = $('#some-overlay'),
    $prompt = $('#some-prompt');

$(document).ready(function () {
  $button.click(function(e) {
    e.preventDefault();

    var args = {
      // ...snip.  Unnecessary.
    };

    $.get('Home/SomeAction', args, function(result) {
      // Some processing...

      // !!!! This is the failing code... !!!!
      $prompt.css({
        'left': (window.width - $prompt.width()) / 2,
        'top': (window.height - $prompt.height()) / 2
      });
    });
  });
});
</script>

定型

.input-eater {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0, 0.5);
}

.overlay {
  position: absolute;
  z-index: 1;
}

.dialogue {
  box-sizing: border-box;
  // Other platform-specific variants also included.
  // Cosmetic attributes such as box-shadow, background color, etc. also set.
}

如上面的脚本部分所述,$.css()调用无法重新定位覆盖范围内的提示。它应该垂直和水平居中,但它仍然位于页面的左上角。

问题:我做错了什么,这是阻止叠加层居中?

1 个答案:

答案 0 :(得分:5)

没有window.widthheight。幸运的是,您可以使用$(window).width()$(window).height()