简体   繁体   English

有没有一种方法可以使用HTML中的JavaScript检测溢出?

[英]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. 我目前正在尝试使用“查看更多”按钮在网页上创建一个包含文本内容的div ,该按钮将允许该框扩展和取消隐藏溢出内容。 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? 有没有办法用JavaScript或其他方式检测到这一点?

See: http://jsfiddle.net/AJ277/ 参见: 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 JS

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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