我有在一個給定的文本框中減小字體大小的算法,如果文本太大的盒子(適合箱)JavaScript的字體大小調整
,它工作得很好,但它確實低效的,因爲它是從字面上看,只需將字體大小減少1直到適合。
任何人都可以幫助我使它更有效率,如二元砍或什麼?
代碼:
function fitToBox(object, maxFontSize, minFontSize, maxHeight) {
var box = document.getElementById(object);
var currentHeight = box.offsetHeight;
var currentFontSize = maxFontSize;
do {
box.style.fontSize = currentFontSize+"pt";
currentFontSize = box.style.fontSize.replace("pt", "");
currentHeight = box.offsetHeight;
if(currentHeight >= maxHeight) {
currentFontSize -= 1;
}
} while (currentHeight > maxHeight && currentFontSize > minFontSize);
box.style.lineHeight = currentFontSize+"pt";
}
在HTML完整的示例(只需添加更多的文本到div看到正在進行的接頭)
<html>
<head>
<script type="text/javascript">
function fitToBox(object, maxFontSize, minFontSize, maxHeight) {
var box = document.getElementById(object);
var currentHeight = box.offsetHeight;
var currentFontSize = maxFontSize;
do {
box.style.fontSize = currentFontSize+"pt";
currentFontSize = box.style.fontSize.replace("pt", "");
currentHeight = box.offsetHeight;
if(currentHeight >= maxHeight) {
currentFontSize -= 1;
}
} while (currentHeight > maxHeight && currentFontSize > minFontSize);
box.style.lineHeight = currentFontSize+"pt";
}
</script>
</head>
<body>
<div id="fitme" style="background-color: yellow; font-size: 24pt; width: 400px;">
This is some text that is fit into the box This is some text that is fit into the box This is some text that is fit into the box
</div>
<script type="text/javascript">
fitToBox("fitme", 24, 4, 80);
</script>
</body>
</html>
它可能有助於看到一些其他的JavaScript和HTML被使用。更具體的是什麼調用這個函數。當我在瀏覽器中試用時,上述功能實際上很麻煩,所以也許我不會按照預期調用它。 – robbieAreBest
我會給原帖 – TheStoneFox