为什么Javascript不与ex单位增加高度?

时间:2017-02-02 14:54:47

标签: javascript html css

我希望JavaScript在css中为当前高度添加高度,它与px单元一起使用,但不与ex单元一起使用。谁知道解决这个问题?

HTML:

<div class="parent">
   <div class="child">
      Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
   </div>
</div>

CSS:

.parent {
   width:150px;
   height:100px;
   float:left;
   background:red;
}

.child {
    line-height:2.5ex;
    max-height:5ex;
    margin:2.5ex;
    background: green;
    overflow: hidden;
}

JavaScript的:

$(document).ready(function(){
  var child = $(".child");

  var height = parseInt(child.css("max-height").split("ex")[0]);

  height = height + 10 ;

  child.css({"max-height": height});

});

2 个答案:

答案 0 :(得分:1)

你应该这样做:child.css({"max-height": height + 'ex'});

答案 1 :(得分:0)

设置CSS属性时,您必须添加ex。来自jQuery docs

  

如果未指定显式单位(如'em'或'%'),则“px”将连接到该值。

$(document).ready(function(){
  var child = $(".child");

  var height = parseInt(child.css("max-height").split("ex")[0]);

  height = height + 10 ;

  child.css({"max-height": height + "ex"});

});
.parent {
   width:150px;
   height:100px;
   float:left;
   background:red;
}

.child {
    line-height:2.5ex;
    max-height:5ex;
    margin:2.5ex;
    background: green;
    overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
   <div class="child">
      Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
   </div>
</div>