2016-10-02 52 views
-1

想象一下具有固定大小的字符串和HTML div元素。通过使用等宽字体和给定的固定字体大小,字符串有多少个字符可以放入div(没有换行)? 奖励:最终如何调整字体大小以使文本真正取得容器的整个宽度。用等宽字体填充固定大小的div

JS

var s = "skjhfkjsdhjfksdhjkghskjgh..."; 

CSS

#c { width:267px; font-size:30px; font-family:monospace } 

HTML

<div id="c"></div> 

看到这个捣鼓一个简易的方法,它的作品,但不是干净的,我猜。可能有更好的办法:https://jsfiddle.net/6et20853/1/

回答

1

你需要.getBoundingClientRect包含一个等宽字符获得一个字符的宽度的元素:如果您想查询

oneCharWidth = document.querySelector('#testing').getBoundingClientRect().width; 
 
console.log(oneCharWidth)
<span id="testing" style="font-family: monospace">a</span>

什么字体大小将允许一串文本适合固定大小的容器:

var widthOfContainer = 400, // The width of the container in pixels 
 
    textLength = "Hello world!".length, // The text to fit 
 
    testElem = document.querySelector('#testing'), 
 
    widthOfChar, 
 
    fontSize = 100; // Our initial guess (must be exaggerated, otherwise optimal value won't be reached) 
 

 
do { 
 
    fontSize--; 
 
    testElem.style.fontSize = fontSize + 'px'; 
 
    widthOfChar = testElem.getBoundingClientRect().width; 
 
} while (textLength * widthOfChar > widthOfContainer); 
 

 
var container = document.querySelector('#container'); 
 
container.style.fontSize = fontSize + 'px'; 
 

 
testElem.parentNode.removeChild(testElem); // Remove #testing element
#container { 
 
    border: 1px solid red; 
 
    font-family: monospace; 
 
    width: 400px; 
 
} 
 

 
#testing { 
 
    font-family: monospace; 
 
}
<div id="container">Hello world!</div> 
 
<span id="testing">a</span>