Issue
I have a div tag with dynamic text value and I want to find how to calculate the number of rows that the string spreads out to according to the font size and the div width
For example:
div {
width: 15px
fontSize: 12px
overflow: hidden
display: block
overflow-wrap: break-word
}
and the string is: "abcdefghijk"
the result in the UI will be:
first row- "abc" second row- "defg" third row- "hijk"
So expected calculation value should be 3 (3 rows).
Is it possible to calculate that?
http://jsfiddle.net/b6upgdqz/15/
Solution
I guess you would have to explicit also the line-height and then divide the total height of the containing div by the line-height you set...
const input = document.getElementById("text");
const container = document.getElementById("container");
const rows = document.getElementById("rows");
input.addEventListener("input", function handleInputChange(event) {
updateRowsCount(event.currentTarget.value);
});
function updateRowsCount(text) {
writeText(text);
computeRows(container);
}
function writeText(text) {
container.innerHTML = text;
}
function computeRows(container) {
const style = window.getComputedStyle(container);
const containerHeight = parseFloat(style.height);
const lineHeight = parseFloat(style.lineHeight);
const rowsCount = Math.ceil(containerHeight / lineHeight);
rows.innerHTML = rowsCount;
}
updateRowsCount(input.value);
#sample {
display: flex;
align-items: flex-start;
}
#sample > * {
margin-right: 2rem;
}
#container {
width: 15px;
font-size: 12px;
line-height: 1.2;
overflow: hidden;
display: block;
overflow-wrap: break-word;
background: pink;
}
<div id="sample">
<input id="text" value="abcdefghijkl" />
<div id="container"></div>
<div id="rows"></div>
</div>
Answered By - 0xc14m1z
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.