2016-10-02 57 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>