【发布时间】:2018-10-15 05:24:47
【问题描述】:
我有一个包含一些图像的容器(砌体网格)。我有一个计算容器宽度的函数和一个计算每个图像宽度的函数。但是获取容器宽度的函数并没有按预期工作,因为宽度包含滚动条。因此图像宽度的计算也是不正确的。
//Function to calculate the width of the container
getContainerWidth() {
const postContainer = document.getElementsByClassName(
'container'
);
if (postContainer.length > 0) {
let containerWidth = postContainer[0].clientWidth;
containerWidth = `${containerWidth}px`;
this.setState({
containerWidth: containerWidth,
});
}
}
我已经尝试过各种功能(offsetWidth、clientWidth、scrollWidth...),但没有一个对我有用。我还尝试获取滚动条的宽度并将其从容器宽度中减去。这行得通,但我需要一个适用于不同浏览器的解决方案。
如果浏览器宽度例如为 1920 像素。那么container-width也是1920px,但应该是1905px(1920-滚动条)。
【问题讨论】:
-
在你的容器里面放一个容器,然后把图片放在里面的容器里面,那有什么作用呢?它是否也包括栏的宽度?
-
我外面已经有一个容器了。我有一个包含页眉、页脚和包含图像的容器的容器。外部容器和带有图像的容器都包括滚动条
-
如果隐藏滚动条是一个选项使用
::-webkit-scrollbar {width: 0px; }然后计算宽度
标签: javascript css