使用JS获取CSS Calc宽度的问题

Jac*_*ler 0 html javascript css css-calc

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

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

上方的蓝色“正方形”不是正方形。能解释为什么吗?而不是clientWidth,我已经尝试过scrollWidthoffsetWidth得到类似的结果。我也没有style.width给出正确的数字。

即使您在Chrome上检查了蓝色正方形,您也会得到一个高度和宽度近似但仍然非常不同的数字。

Tem*_*fif 5

两个问题。首先,您需要考虑填充,因此添加box-sizing:border-box后再使用vw单位定义宽度,因此只有在第一次打开页面且从不调整浏览器大小时,才会出现空白。

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

如果要使正方形保持在窗口大小上,则需要使用相同的指定值,而不要使用以像素为单位的计算值(如何使用JavaScript读取CSS规则值?

或更改调整大小的值:

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

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


附带说明一下,您可以考虑将CSS变量仅指定一次相同的值,或者检查一下:使用CSS保持div的长宽比

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