gpt4 book ai didi

javascript - 为什么没有滚动条我无法获取容器宽度?

转载 作者:行者123 更新时间:2023-11-28 01:46:04 29 4
gpt4 key购买 nike

我有一个带有一些图像的容器(砌体网格)。我有一个计算容器宽度的函数和另一个计算每个图像宽度的函数。但是获取容器宽度的函数并不像预期的那样工作,因为宽度包含滚动条。因此图像宽度的计算也不正确。

//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...),但没有一个对我有用。我还尝试获取滚动条的宽度并将其从容器宽度中减去。这行得通,但我需要一个适用于不同浏览器的解决方案。

如果浏览器宽度为 1920px。那么container-width也是1920px,不过应该是1905px(1920-scrollbar)。

最佳答案

获取ClientWidth

The Element.clientWidth property is zero for elements with no CSS or inline layout boxes, otherwise it's the inner width of an element in pixels. It includes padding but not the vertical scrollbar (if present, if rendered), border or margin.

例子

var width = element.clientWidth;

关于javascript - 为什么没有滚动条我无法获取容器宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50179741/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com