简体   繁体   中英

Is there a way to detect overflow using JavaScript in html?

I'm currently attempting to make a div with text content on a web page with a "see more" button that will allow the box to expand and un-hide the overflow content. However I only want the "see more" to be visible if there is actually overflow.

Is there some way, in JavaScript, or otherwise that I can detect this?

See: http://jsfiddle.net/AJ277/

if (element.scrollHeight > element.offsetHeight) {
    alert('Overflow!');
}

Fiddle

You could simply add a wrapper around the text and compare the wrapper height to the parent height.

FIDDLE

JS

if ($('.wrapper').height() > $('#text').height()) {
    //do stuff
}
else { 
    //do other stuff like hide buttons 
}

HTML

<div id="text">
    <div class="wrapper">Lorem ipsum dolor sit amet, consectetur adipiscing elit. In in rutrum lorem. Donec eget turpis arcu. Fusce at neque libero. Nam sed risus velit. Fusce eleifend leo ac laoreet dapibus. Morbi vel tincidunt tortor. Vivamus placerat elit nec mi pulvinar, vitae volutpat nisi tempus.</div>
</div>
<button id="show">show more (only show this button if there is overflow)</button>
<button id="hide" style="display: none">hide</button>

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