Determine if an HTML element's content overflows

前端 未结 6 1014
误落风尘
误落风尘 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 05:50

    This is a javascript solution (with Mootools) that will reduce the font size to fit the bounds of elHeader.

    while (elHeader.clientWidth < elHeader.scrollWidth || elHeader.clientHeight < elHeader.scrollHeight) {
      var f = parseInt(elHeader.getStyle('font-size'), 10);
      f--;
      elHeader.setStyle('font-size', f + 'px');
    }
    

    The CSS of elHeader:

        width:100%;
        font-size:40px;
        line-height:36px;
        font-family:Arial;
        text-align:center;
        max-height:36px;
        overflow:hidden;
    

    Note the wrapper of elHeader sets the width of elHeader.

提交回复
热议问题