javascript - 为什么 scrollWidth 只包括左填充?

标签 javascript html css browser cssom

所以,我有一个具有固定宽度的 DIV #Wrapper。在那个 DIV 中,我有另一个 DIV #Panel,它也有一个固定的宽度:

<div id="Wrapper">
    <p>...</p>
    <div id="Panel">Panel</div>
    <p>...</p>
</div>  

有时,Panel 的宽度大于 Wrapper 的宽度,在这种情况下,我想通过 JavaScript 加宽 Wrapper,以便它完美地包裹 Panel。

现场演示: http://jsfiddle.net/H6rML/

我打算在 Wrapper 上使用 .scrollWidth 来确定面板的宽度。但是,问题在于包装器具有水平填充,而 .scrollWidth 由于某种原因仅包含包装器的左侧填充。所以:

Wrapper.scrollWidth === Wrapper.LeftPadding + Panel.Width

所以,给定:

#Wrapper {
    width: 200px;
    padding: 10px;        
}

#Panel {
    width: 300px;
}

Wrapper.scrollWidth 返回 310px,这不是很有用。如果 .scrollWidth 不包含任何填充并且只返回面板的宽度,我可以使用它(我会手动将填充添加到该值)。如果两个填充都包括在内,我也可以使用它。但为什么只包括左填充? (顺便说一下,这种行为似乎是跨浏览器的。)

一些附加说明:

  1. 我无法直接在 Wrapper 上设置宽度。在我的实际代码中,我在 Wrapper 之上几层的祖先元素上设置了宽度,并且我使用自定义 API 来设置宽度。这就是为什么我需要检索完整的 320px 值。

  2. 我想要一个不依赖于 Wrapper 内容的解决方案。在我的演示中,它是一个面板,但在其他情况下,可能会有一个不同的元素溢出,甚至是多个元素。这就是我在 Wrapper 上使用 .scrollWidth 的原因。

有没有一种方法可以获取值 320px 而无需手动将正确的填充添加到 .scrollWidth 值?


顺便说一句,根据标准,应该包含正确的填充:

The scrollWidth attribute must return the result of running these steps:

  1. If the element does not have any associated CSS layout box return zero and terminate these steps.

  2. If the element is the root element and the Document is not in quirks mode return max(document content width, value of innerWidth).

  3. If the element is the HTML body element and the Document is in quirks mode return max(document content width, value of innerWidth).

  4. Return the computed value of the 'padding-left' property, plus the computed value of the 'padding-right', plus the content width of the element.

来源:http://www.w3.org/TR/cssom-view/

为什么浏览器没有相应的行为?


为了进一步提高我帖子的清晰度,让我总结两个主要问题:

(1) 如果标准声明正确的填充应该包含在 .scrollWidth 值中,那么为什么浏览器不相应地运行?

(2) 是否可以检索正确的值(在我的例子中是 320px),而无需手动添加正确的填充?


这个问题已经在另一个帖子中回答了

此问题的答案位于此处:When a child element overflows horizontally, why is the right padding of the parent ignored?

最佳答案

我不确定我是否理解正确,但从我读到的内容来看,我假设你想根据#Panel 更改#Wrapper 的宽度。在这种情况下,也许您可​​以尝试以下操作:

#Wrapper {
    display: inline-block;
    make sure to remove width from #Wrapper
}

关于javascript - 为什么 scrollWidth 只包括左填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10044551/

相关文章:

jquery - 禁用可点击的 div,直到函数被执行。

css - 清除没有显示属性的 float

javascript - 带有动态 div 的 JQuery 对话框

php - 转换为 HTTPS

javascript - 仅提交 angularjs 中表单的检查值

javascript - 从 HTMLVideoElement 中提取帧

javascript - 预填充值形成时覆盖标签

javascript - 如何创建一个大的导航菜单

javascript - 不要在触摸设备上显示悬停状态

javascript - Google 跟踪代码管理器使用什么模式来观察 `dataLayer` 数组?