小编典典

确定HTML元素的内容是否溢出

html

我可以使用JavaScript检查(与滚动条无关)HTML元素的内容是否溢出?例如,一个长div,具有固定的小尺寸,overflow属性设置为visible,并且元素上没有滚动条。


阅读 433

收藏
2020-05-10

共1个答案

小编典典

通常,您可以比较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中进行了测试。

2020-05-10