有没有办法在 html 中使用 JavaScript 检测溢出

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

本文关键字:JavaScript 检测 溢出 html 有没有      更新时间:2023-09-26

我目前正在尝试使用带有"查看更多"按钮的网页上的文本内容进行div,该按钮将允许该框展开并取消隐藏溢出内容。但是,如果确实有溢出,我只希望"看到更多"是可见的。

有没有办法,在 JavaScript 或其他方面我可以检测到这一点?

请参阅:http://jsfiddle.net/AJ277/

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

小提琴

您可以简单地在文本周围添加一个包装器,并将包装器高度与父高度进行比较。

小提琴

.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>