如何使用纯JS使宽度等于高度成为CSS规则



如何使用纯JS在CSS规则中使宽度等于高度?也许,CSS中有一个解决方案。

CSS

#animation-2 > div.line {
height: 10%;
background: red;
}

JS-

let line = document.querySelector('.line');
let height = line.offsetHeight;
document.querySelector('.line').style.width = height;

它不起作用。我想要像素值。我可以忘记加些什么吗?

THanks

您忘记了"px";后缀:

let line = document.querySelector('.line');
let height = line.offsetHeight;
document.querySelector('.line').style.width = height + 'px';

https://jsfiddle.net/yr5eu2gn/

存储在line.offsetHeight中的值是一个计数像素的number,而elem.style.width需要一个带单位的字符串。

因此,您必须编写

document.querySelector('.line').style.width = height + 'px';

offsetHeight不获取百分比大小。它以像素为单位。所以,你也需要得到父母的身高,以计算出百分比的大小。

此外,您需要添加您想要使用的单元,并且Javascript只保存数字。

编辑:嗯。。。刚刚看到你的编辑,你想要的是像素,而不是百分比。希望这能帮助到别人。

let line = document.querySelector('.line');
let height = line.offsetHeight;
let parentHeight = line.offsetParent.offsetHeight;
let percentHeight = Math.round(100 * height / parentHeight);
line.style.width = percentHeight+"%";
line.innerHTML = percentHeight;
#animation-2{
height: 100vh;
}
#animation-2 > div.line {
height: 10%;
background: red;
}
<div id="animation-2">
<div class="line"></div>
</div>

最新更新