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

129 html javascript css

如果HTML元素溢出其内容,我可以使用JavaScript检查(无论滚动条)吗?例如,一个长小的固定大小的div,溢出属性设置为可见,并且元素上没有滚动条.

Sho*_*og9 205

通常情况下,你可以比较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;
}
Run Code Online (Sandbox Code Playgroud)

测试在FF3,FF40.0.2,IE6,Chrome 0.2.149.30中.

  • +1.这适用于现代浏览器(从撰写本文时起至少包括Chrome 40和其他当前版本的浏览器). (3认同)
  • 我想知道这样的风格是否会短暂闪烁? (2认同)

Ali*_*nes 6

另一种方法是将元素宽度与其父元素宽度进行比较:

function checkOverflow(elem) {
    const elemWidth = elem.getBoundingClientRect().width
    const parentWidth = elem.parentElement.getBoundingClientRect().width

    return elemWidth > parentWidth
}
Run Code Online (Sandbox Code Playgroud)

  • 子元素通常被包含或缩小以适合父元素。你如何解决这个问题? (3认同)