开发者

How can you tell when a <div> is full of text?

开发者 https://www.devze.com 2022-12-12 20:20 出处:网络
Imagine a website with an element The site wants to run some JS which will fill the div with random text, when the div is full it should clear and start over. Yes I know that sounds wei开发者_开发技巧

Imagine a website with an element The site wants to run some JS which will fill the div with random text, when the div is full it should clear and start over. Yes I know that sounds wei开发者_开发技巧rd but the question is, how can the JS know when the div is full, and would start to overflow?

By 'full', I mean no more visible text can be put in the div. I suppose this is the point a scroll bar would become enabled/visible.


What you could do would be to actually have the text in an inner div, that has the same fixed width as the container, but no fixed height. You'd then let the inner div grow with its content, and check when its height approaches the parent div's fixed height


You could compare the actual height of the div against what is defined in the CSS for that div, to see if the actual height is greater - and therefore is 'overflowing'.

if(document.getElementById('div').offsetHeight > 
document.getElementById('div').style.height) {
   //do something
}


You can't tell if any more text will cause an overflow... maybe the text is just one tiny i, or even a load of zero-width-spaces. All you can do is add the text and see if it overflows afterwards.

var hasoverflowed= div.offsetHeight<div.scrollHeight;
// more or less... modulo borders


Assuming your div is fixed height, set overflow:hidden and check the div.scrollHeightproperty.

if(myDiv.scrollHeight > myDiv.offsetHeight) { /* the div is full */ }
else { /* there is room left */ }


You should be able to get very close by counting the characters in the div. You might need to do this onkeyUp if you're typing, or listen for some other event if it's not being filled by typing.

0

精彩评论

暂无评论...
验证码 换一张
取 消