使用 JS 获取 CSS 计算宽度的问题

Issue getting CSS calc width with JS

我需要制作一个基于屏幕宽度的方形元素。为了将高度设置为与宽度相同,我尝试使用 JS,但似乎有点错误。这是一个例子

var square = document.getElementById('square');
square.style.height = square.clientWidth + 'px';
#square {
  background-color: blue;
  width: calc(20vw - 16px);
  padding: 8px;
}
<div id="square">Element</div>

上面的蓝色"square"不是正方形。任何人都可以解释为什么吗?我尝试了 scrollWidthoffsetWidth,而不是 clientWidth,结果相似。我也没有 style.width 给出正确的数字。

即使您检查 Chrome 上的蓝色方块,您也会得到一个高度和宽度的数字,它们很接近但仍然有很大差异。

两个问题。首先你需要考虑填充,所以添加 box-sizing:border-box 然后你使用 vw 单位定义宽度,所以当你打开页面时你将有一个正方形 only第一次 从不 调整浏览器大小。

var square = document.getElementById('square');
square.style.height = square.clientWidth + 'px';
#square {
  background-color: blue;
  width: calc(20vw - 16px);
  padding: 8px;
  box-sizing:border-box;
}
<div id="square">Element</div>

如果您想要一个保持 window 调整大小的正方形,您需要使用相同的指定值而不是像素计算值 (How do you read CSS rule values with JavaScript?)

或在调整大小时更改值:

var square = document.getElementById('square');
square.style.height = square.clientWidth + 'px';

window.onresize=function() {
  square.style.height = square.clientWidth + 'px';
};
#square {
  background-color: blue;
  width: calc(20vw - 16px);
  padding: 8px;
  box-sizing:border-box;
}
<div id="square">Element</div>


作为旁注,您可以考虑 CSS 变量仅指定一次相同的值或检查此:Maintain the aspect ratio of a div with CSS

#square {
  --v:calc(20vw - 16px);
  background-color: blue;
  width: var(--v);
  height: var(--v);
  padding: 8px;
  box-sizing:border-box;
}
<div id="square">Element</div>

您可以对高度使用相同的计算器

width: calc(20vw - 16px);
height: calc(20vw - 16px);