簡體   English   中英

如何將font-size設置為div大小的100%?

[英]How to set the font-size to 100% the size of a div?

我有一個靜態尺寸的div。 有時,比div長的文本將被放置在那里。 無論如何,是否通過JavaScript就能始終實現適合div寬度的文本? 我知道有jQuery修復程序,但在這種情況下需要純JS解決方案。

即使您有指向演示/教程的鏈接也可能會有所幫助,謝謝。

到這里,這應該做您想要的: JSFiddle

基本上,這里的關鍵是對照output.height檢查output.scrollHeight 請考慮以下設置:

HTML:

<button onclick="addText(); resizeFont()">Click Me to Add Some Text!</button>
<div id="output"></div>

CSS:

div {
    width: 160px;
    height: 160px;
}

這將創建一個Square div,並通過addText()方法將其隨機長字符串填充。

function addText() {
    var text   = "Lorem ipsum dolor amit",
        len    = Math.floor(Math.random() * 15),
        output = document.querySelector('#output'),
        str    = [];
    for (; --len;)
        str.push(text);

    output.innerHTML = str.join(', ');
}

魔術在於resizeFont()函數。 基本上,這樣做是在添加文本之后,將divfontSize設置為其自己的高度。 這是當您具有1個字符的字符串(即fontSize將等於高度)時的基本情況。 隨着字符串長度的增加,需要將fontSize減小,直到scrollHeight等於div的高度。

function resizeFont() {
    var output   = document.querySelector('#output'),
        numRE    = /(\d+)px/,
        height   = numRE.exec(window.getComputedStyle(output).height)[1],
        fontSize = height;

    // allow div to be empty without entering infinite loop
    if (!output.innerHTML.length) return;

    // set the initial font size to the height of the div
    output.style.fontSize = fontSize + 'px';

    // decrease the font size until the scrollHeight == height
    while (output.scrollHeight > height)
      output.style.fontSize = --fontSize + 'px';
}

關於此方法的好處是,您可以輕松地將事件偵聽器附加到窗口的resize事件,使文本隨着用戶更改窗口大小而動態地調整大小: http : //jsfiddle.net/QvDy8/2/

window.onload = function() {
  window.addEventListener('resize', resizeFont, false);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM