调整字体大小以适合父容器中的文本

时间:2019-06-28 18:41:17

标签: javascript css

我试图调整元素的字体大小,以便其文本正确适合容器,然后我想到了这个for循环。恐怕这可能会导致性能问题,所以我想知道是否有更好的方法-最好没有Java语言?

const txt = $("#text");
const box = $("#box");

let size = 5; // minimum font size
let found = false;
do {
  txt.css('font-size', `${size}pt`);
  if(txt.height() < box.height() && txt.width() < box.width()) {
    size+=.1;
  } else {
    found = true;
  }
} while(!found);
#box {
  background-color: green;
  display: block;
  height: 120px;
  width: 100%;
}
#text {
  background:red;
  display: inline;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="box">
  <div id="text">
    This is a sample test. This is a sample test.<br />
    This is a sample test. This is a sample test.<br />
    This is a sample test. This is a sample test.    
  </div>  
</div>

0 个答案:

没有答案
相关问题