I have this unique situation in front of me where i want create a function to show only 8 lines of text whatsoever. The website is responsive. Here is what i have tried:
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);
The Problem:
<p>
width is 600px then it is obvious that 900 words wont fit in one line.. the browser will wrap the text to new lines.. but what does the browser do to achieve this, does it insert a new line character \\n
? 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}
The easy css solution would be to set the container's height to 8em
and set overflow to hidden
.
In practice I have found this to be inaccurate. Here is a jQuery solution (assume I have a div
with the id of bozo
):
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);
#bozo {
overflow: hidden;
width:100%;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.