Determine if an HTML element's content overflows

前端 未结 6 1008
误落风尘
误落风尘 2020-11-22 05:19

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 proper

6条回答
  •  星月不相逢
    2020-11-22 06:03

    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;
    }
    

    Tested in FF3, FF40.0.2, IE6, Chrome 0.2.149.30.

提交回复
热议问题