确定 HTML 元素的内容是否溢出 [英] Determine if an HTML element's content overflows
问题描述
我可以使用 JavaScript 来检查(不考虑滚动条)HTML 元素是否溢出了其内容?例如,一个小的、固定大小的长 div,overflow 属性设置为可见,元素上没有滚动条.
Can I use JavaScript to check (irrespective of scrollbars) if an HTML element has overflowed its content? For example, a long div with small, fixed size, the overflow property set to visible, and no scrollbars on the element.
推荐答案
通常可以比较client[Height|Width]
和scroll[Height|Width]
为了检测到这一点......但是当溢出可见时,这些值将相同.因此,检测程序必须考虑到这一点:
Normally, you can compare the client[Height|Width]
with scroll[Height|Width]
in order to detect this... but the values will be the same when overflow is visible. So, a detection routine must account for this:
// Determines if the passed element is overflowing its bounds,
// either vertically or horizontally.
// Will temporarily modify the "overflow" style to detect this
// if necessary.
function checkOverflow(el)
{
var curOverflow = el.style.overflow;
if ( !curOverflow || curOverflow === "visible" )
el.style.overflow = "hidden";
var isOverflowing = el.clientWidth < el.scrollWidth
|| el.clientHeight < el.scrollHeight;
el.style.overflow = curOverflow;
return isOverflowing;
}
在 FF3、FF40.0.2、IE6、Chrome 0.2.149.30 中测试.
Tested in FF3, FF40.0.2, IE6, Chrome 0.2.149.30.
这篇关于确定 HTML 元素的内容是否溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!