I am getting long text using ajax in json form I want to fill those content in the fix height div
suppose I have div height 500px and width 300px. and font size is 16px
i want any javascript recursive method that can fill data according to height and width of div and can return me remaining text.
if any one can do that then Please provide me solution.
Thanks in Advance
First of all, wrap the text inside a <span>
in put it in your <div>
. I'm assuming that div
is your fixed size element here:
// Be careful about text nodes, or use firstElementChild instead
var span = div.firstChild, text = span.innerText, rest = "";
if (span.offsetHeight > 500) {
var totalLength = 0, markLength, i = 0,
rects = span.getClientRects();
for (; i < rects.length; i++) {
totalLength += rects[i].right - rects[i].left;
if (rects[i].bottom - rects[0].top <= 500)
markLength = totalLength;
}
var mark = Math.floor(text.length * markLength / totalLength);
span.textContent = text.substring(0, mark);
rest = text.substring(mark);
}
The variable rest
contains the remaining part. Beware that this method uses some approximations, and sometimes may not fill the container to the brim. In some unlucky cases, it may even overflow the container, so you have to run it again until you get the correct size.
Why don't just put all in the div and in the div you set overflow="hidden"
Create a temp div, fix it width and append text until it exceed your height then stop, after that copy all content to the main div
var s = 'Your long long long long long long long long long long content';
var i = 0;
var tmpdiv = $('<div style="width:50px; height:auto; position:absolute; left:-99999px"/>').appendTo(document.body);
while (i < s.length-1 && tmpdiv.height() < 50){
tmpdiv.append(s[i]);
i++;
}
$('#fixdiv').html(tmpdiv.html());
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.