简体   繁体   中英

Find div width that makes the text inside not wrapped

I built a CRM with some javascript to adjust the columns widths as the user wants, but I would like to have a button to automatically adjust the width of all column. The idea is to check each div to verify if the text is wrapped and if so, increase the div width (within a given limit) or reduce in the opposite case. Something like that:

while(div.contentTextWrapped && parseInt(div.style.width)>50)
{
     div.style.width=parseInt(div.style.width)-5+"px";
}
while(div.contentTextWrapped && parseInt(div.style.width)<500)
{
     div.style.width=parseInt(div.style.width)+5+"px";
}

But I don't know such feature. Maybe I could set the white-space to nowrap and check the width but I need the content is not an element, or maybe I need to add a div inside and then I could check its width and compare ?

You can try to find width of one character. then get whole text of your div and calculate total size of div:

const singleCharWidth = 3; // in px
const textLength = div.textContent.length;
div.style.width = `${textLength * singleCharWidth}px`;

If you want to read more about calculating text width you can read more about this here: Calculate text width with JavaScript

I think you have to calculate number of lines and then adjust width of object. There are a lot of ways to do that, here's one approach:

 function findWidth(obj, minW, maxW) { let lines, ref, lineHeight, wdt, dif=10, done=false; // Get line height from myDummy ref=document.getElementById('myDummy') lineHeight=ref.offsetHeight; if(lineHeight==0) return // Assign min widht to start wdt=minW; obj.style.width=wdt+'px'; lines=Math.round(obj.offsetHeight/lineHeight); while(lines>1) { // Get current width and increase or assign max / min and exit wdt=parseInt(obj.style.width); if(wdt+dif>maxW) { wdt=maxW; done=true; } else if(wdt<minW) { wdt=minW; done=true; } else { wdt+=dif; } obj.style.width=wdt+'px'; if(done) break; lines=Math.round(obj.offsetHeight/lineHeight); } } // Some tests... findWidth(document.getElementById('myDiv1'), 25, 200); findWidth(document.getElementById('myDiv2'), 25, 200); findWidth(document.getElementById('myDiv3'), 25, 200);
 #myDummy { visibility: hidden; } div { border: 1px solid crimson; }
 <div id="myDummy">&nbsp;</div> <div id="myDiv1"> This is some text... </div> <div id="myDiv2"> This is some text... with more and more and more and more and more... </div> <div id="myDiv3"> T... </div>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM