我试图调整元素的字体大小,以便其文本正确适合容器,然后我想到了这个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>