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

我可以使用 JavaScript 来检查(不管滚动条) HTML 元素是否溢出了它的内容吗?例如,一个大小固定的长 div,溢出属性设置为可见,元素上没有滚动条。

88072 次浏览

通常,您可以将 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中测试。

我不认为这个答案是完美的,有时 scrollWidth/clientWidth/offsetWidth 是相同的,即使文本已经溢出。

这在 Chrome 中很管用,但在 IE 和 Firefox 中就不行了。

最后,我尝试了这个答案: HTML 文本溢出省略检测

它是完美的,适用于任何地方。所以我选择了这个,也许你可以尝试,你不会失望。

这是一个 javascript 解决方案(使用 Mootools) ,它将减小字体大小以适应 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');
}

ElHeader 的 CSS:

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

注意,elHeader 的包装器设置 elHeader 的宽度。

使用 jQuery 你可以做到:

if ( $(".inner-element").prop('scrollHeight') > $(".inner-element").height() ) {


console.log("element is overflowing");


} else {


console.log("element is not overflowing");


}

如果需要,改为 .prop('scrollWidth').width()

另一种方法是比较元素的宽度和父元素的宽度:

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


return elemWidth > parentWidth
}