确定HTML元素的内容是否溢出
时间:2020-03-06 14:49:33 来源:igfitidea点击:
是否可以使用JavaScript检查(与滚动条无关)HTML元素的内容是否溢出?例如,一个长div,具有固定的小尺寸,overflow属性设置为visible,并且元素上没有滚动条。
解决方案
尝试将element.scrollHeight / element.scrollWidth与element.offsetHeight / element.offsetWidth进行比较
http://developer.mozilla.org/en/DOM/element.offsetWidth
http://developer.mozilla.org/en/DOM/element.offsetHeight
http://developer.mozilla.org/en/DOM/element.scrollWidth
http://developer.mozilla.org/en/DOM/element.scrollHeight
通常,我们可以将" client [Height | Width]"与" scroll [Height | Width]"进行比较,以便检测到此情况...但是当可见溢出时,这些值将相同。因此,检测例程必须考虑到这一点:
// 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中进行了测试。