1

目の前に、8行のテキストのみを表示する関数を作成したいというユニークな状況があります。ウェブサイトはレスポンシブです。これが私が試したことです:

var fontSize = $target.css("font-size").match(/\d/g).join(""),
lineWidth = $target.width(),
totalLetters = $target.text().length,
lettersPerLine = (totalLetters * fontSize) / lineWidth,
numOfLines = Math.round(totalLetters/lettersPerLine);

問題:

  1. 私が使用しているフォントはモノスペースではありません。つまり、すべての文字が同じ幅であるとは限りません。
  2. WordsPerLine をパラメーターとして関数に渡したくありません。これを計算させたいのです。
  3. ブラウザがテキストを新しい行に折り返すために何をしているのかわかりません/わかりません。たとえば、<p>幅が 600px の場合、900 語が 1 行に収まらないことは明らかです.ブラウザはテキストを新しい行に折り返すでしょう..しかし、これを達成するためにブラウザは何をしますか?改行文字を挿入しますか? \n?
  4. 上記のコードは私には機能しません。理由がわかりません...手がかりがあれば(賢い人は私が間違っていることを間違いなく知っていると確信しています)、光を当ててください。すべての提案に深く感謝いたします。
4

2 に答える 2

3

After wanting to know this a few times, a soultion I came up with is pre-calculating the height and width the characters by having them rendered, cache this and produce a lookup function.

The following works as long as body > span will be rendered. The parameters are optional, defaulting to the style of body > span and the first 255 chars of the font.

function charSizes(numChars, cssFont) {
    var span = document.createElement('span'),
        text = document.createTextNode(''),
        uia, i, j;
    span.appendChild(text);
    if (cssFont) span.style.font = cssFont;
    span.style.padding = span.style.margin = 'none';
    document.body.appendChild(span);
    numChars = (numChars || 255);
    uia = new Uint32Array(numChars * 2);
    for (j = i = 0; i < numChars; j = 2 * ++i) {
        text.data = String.fromCharCode(i);
        uia[j] = span.offsetWidth;
        uia[j + 1] = span.offsetHeight;
    }
    // free memory
    document.body.removeChild(span);
    span = text = numChars = cssFont = null;
    // output lookup function
    return function (c) {
        var i = c.charCodeAt(0) * 2;
        return {
            width: uia[i],
            height: uia[i + 1]
        };
    };
}

var arial12 = charSizes(0xFF, '12px Arial');

Now you can look up characters easily

arial12('a'); // {width: 7, height: 15}
arial12('-'); // {width: 5, height: 15}
于 2013-08-16T20:57:36.440 に答える
1

簡単な CSS ソリューションは、コンテナーの高さを8emに設定し、オーバーフローを に設定することhiddenです。

実際には、これは不正確であることがわかりました。ここにjQueryソリューションがあります(divのIDを持つ があると仮定しますbozo):

JavaScript

function getFontHeight(className) {
    $testdiv = $('<div stlye="white-space:nowrap;">jgpqAZ</div>');
    if (className) $testdiv.addClass(className);
    $('body').append($testdiv);
    var height = $testdiv.innerHeight();
    $testdiv.remove();
    return height;
}

$('#bozo').height(getFontHeight() * 8);

CSS

#bozo {
    overflow: hidden;
    width:100%;
}

jsフィドル

于 2013-08-16T20:31:21.063 に答える