我需要制作一个基于屏幕宽度的方形元素。为了将高度设置为与宽度相同,我尝试使用 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>
上面的蓝色“正方形”不是正方形。任何人都可以解释为什么吗?我尝试使用 scrollWidth
和 offsetWidth
,而不是 clientWidth
,结果相似。我也没有得到 style.width
来给出正确的数字。
即使您在 Chrome 上检查蓝色方 block ,您也会得到一个高度和宽度的数字,它们很接近但仍然有很大差异。
最佳答案
两个问题。首先你需要考虑填充,所以添加 box-sizing:border-box
然后你使用 vw
单位定义宽度,所以你将有一个正方形 当您第一次打开该页面并且从不调整浏览器大小时。
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>
如果你想要一个保持在窗口调整大小的正方形,你需要使用相同的指定值而不是像素计算值(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>
关于javascript - 使用 JS 获取 CSS 计算宽度的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54698433/