代码之家  ›  专栏  ›  技术社区  ›  Val

jquery height()问题

  •  1
  • Val  · 技术社区  · 15 年前

    这让我很生气,有人帮忙,因为我好像不知道问题在哪里。

    <div id="parent">
       <div id="child"></div>
    </div>
    <script>
       $('#parent').height(300)
    
       $('#child').height($('#child').parent().height()-10); //EDITTED LINE
    </script>
    

    以上是我需要做的事情的逻辑。 我检查了“parent”的html标签,上面写着style=“height:300px;” 然而,孩子的值为-10:(应该是290; 我已经签入了dom,值是正确的,我还尝试了.css(“height”)。 但没有运气。 有人遇到过这种问题吗?如果是这样的话,解决方法是什么:)把我从误会中救出来

    抱歉,伙计们,问题出在“parent().height()”上。再次看到脚本(再次抱歉)

    3 回复  |  直到 15 年前
        1
  •  3
  •   balupton    15 年前

    .height() 有时会在附加“px”的情况下获取它。您必须删除“px”,否则将执行此操作。 '300px' - 10 . 您可以通过以下方式完成此操作:

    var height = parseInt($('#el').height(),10);
    

    把它转换成数字。

    像这样的, 您的代码应更改为:

    $('#child').height($('#child').parent().height()-10);
    

    到:

    $('#child').height(parseInt($('#child').parent().height(),10)-10);
    

    或者更好的方法,在代码中添加缓存,使其更快! (你不必重新蚀刻孩子。)

    var $child = $('#child');
    $child.height(parseInt($child.parent().height(),10)-10);
    

    您的第一行代码中还忘了分号,但是我的代码与此无关。

        2
  •  0
  •   chahedous    15 年前

    尝试在之前创建变量

    var childheight = $('#parent').height()-10;
    $('#child').height(childheight);
    
        3
  •  -1
  •   James    15 年前

    为什么不把它设为290?

    $('#child').height(290);