我想确定元素是否溢出,标准的
el.clientWidth < el.scrollWidth
在Chrome中工作得很好,但由于某种原因,它在Firefox中存在一些问题。
我的元素有
box-sizing: border-box
+ 一些 0.75rem 的填充。当元素的溢出恰好落在 0.75rem 内时,Firefox 会显示溢出,但 scrollWidth
不会改变。
为什么我这么认为? 因为当我更改
clientWidth
属性时,Chrome 中的 box-sizing
也会发生变化,而 Firefox 中则相反。
那么我怎样才能检查一个在所有浏览器中都有效的元素的溢出状态呢?
要以在不同浏览器(例如 Chrome 和 Firefox)中一致的方式检查元素的溢出状态,您可以使用多种方法的组合来确保稳健性。这是一个可靠的方法:
接近
1。检查scrollWidth是否超过clientWidth: 这是检查元素是否水平溢出的最常用方法。但是,您已经注意到 Firefox 的一些不一致之处,特别是在处理框大小和填充时。
2。使用包装元素: 将元素包装在容器中,可以帮助您隔离溢出问题。这还可以为您提供更一致的方法来确定溢出。
3.考虑使用 getCompatedStyle 来调整框大小: 如果需要,检索框大小属性以调整计算。
4。实现一个检查溢出的函数: 将这些策略组合成一个函数,可以可靠地确定元素是否溢出。
示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.container {
overflow: hidden;
width: 100%;
}
.element {
box-sizing: border-box;
padding: 0.75rem;
width: 200px;
border: 1px solid black;
}
</style>
<title>Overflow Check</title>
</head>
<body>
<div class="container">
<div class="element">This is a test element with some content that might overflow.</div>
</div>
<script>
function isElementOverflowing(el) {
const computedStyle = window.getComputedStyle(el);
const boxSizing = computedStyle.boxSizing;
const paddingLeft = parseFloat(computedStyle.paddingLeft);
const paddingRight = parseFloat(computedStyle.paddingRight);
const borderLeft = parseFloat(computedStyle.borderLeftWidth);
const borderRight = parseFloat(computedStyle.borderRightWidth);
const clientWidth = el.clientWidth;
const scrollWidth = el.scrollWidth;
if (boxSizing === 'border-box') {
// In border-box, padding and border are included in the width
return scrollWidth > clientWidth;
} else {
// In content-box, padding and border are not included in the width
return scrollWidth > (clientWidth - paddingLeft - paddingRight - borderLeft - borderRight);
}
}
const element = document.querySelector('.element');
console.log('Is element overflowing?', isElementOverflowing(element));
</script>
</body>
</html>
说明:
1。 CSS:
1. container: Provides a boundary for overflow checking.
2. element: The element to check for overflow, with box-sizing: border-box and padding applied.
2。 JavaScript:
window.getCompulatedStyle(el):检索计算样式以处理框大小、填充和边框。
clientWidth 和scrollWidth:clientWidth 是元素的可见宽度,而scrollWidth 是包括溢出在内的完整宽度。
boxSizing 检查:根据 box-sizing 属性调整计算。
注意事项:
通过使用这种方法,您可以更可靠地确定元素是否溢出,而不管浏览器特定的怪癖如何。