【问题标题】:jQuery doesn't take the correct div heightjQuery 没有采用正确的 div 高度
【发布时间】:2014-03-17 21:30:14
【问题描述】:

我的 jQuery 有问题:我使用的脚本允许我通过给元素一个类来居中元素,但是这个脚本没有采用正确的高度。

这是我的 HTML 代码:

    <div class="logoutscreen blackbackground">
        <div class="window centered" style="display: block;">
       [CONTENT HERE]
       </div>
    </div>

这是我的 jQuery 代码:

$(function () {
    $(".centered").css({
        'position': 'absolute',
        'left': '50%',
        'top': '50%',
        'margin-left': -$(this).outerWidth() / 2,
        'margin-top': -$(this).outerHeight() / 2
    });
});

问题在于脚本不采用具有 .centered 类 (.window) 的 div 的高度和宽度,而是采用其父级 (.logoutscreen) 的高度和宽度。

为什么会这样? :(

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    $(this) 的使用是你的问题。与其他方法不同,您不能在 jQuery 的 .css() 方法中以 $('.centered') 的形式访问 this 父对象...它将默认为全局 window 对象。

    你想要做的是缓存你的对象并明确引用它:

    var $centered = $('.centered');
    
    $centered.css({
        position:'absolute',
        left:'50%',
        top:'50%',
        marginLeft:((-1 * $centered.outerWidth()) / 2),
        marginTop:((-1 * $centered.outerHeight()) / 2)
    });
    

    这应该会给你你正在寻找的东西。但是,如果您有多个实例,则需要执行以下操作:

    $centered.each(function(){
        var $self = $(this);
    
        $self.css({
            position:'absolute',
            left:'50%',
            top:'50%',
            marginLeft:((-1 * $self.outerWidth()) / 2),
            marginTop:((-1 * $self.outerHeight()) / 2)
        });
    });
    

    这样每个独特的 heightwidth 都会受到尊重。

    【讨论】:

      【解决方案2】:

      this 不是$('.centered')

      用途:

      $(function () {
          var centered = $('.centered').first();
          centered.css({
              'position': 'absolute',
              'left': '50%',
              'top': '50%',
              'margin-left': -centered.outerWidth() / 2,
              'margin-top': -centered.outerHeight() / 2
          });
      });
      

      【讨论】:

      • @DOCTYPEHTML,对不起,我没听懂。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多