javascript - 通过 Javascript 分配 CSS 值

标签 javascript html css

<分区>

我想使用 Javascript 应用 CSS。 我将#test-div 的宽度分配给 var 'wid',然后将相同的值分配给#test-div 的高度。 然而,高度的值并没有改变。

var wid = document.getElementById("test-div").style.width
document.getElementById("test-div").style.height = wid
#test-div {
  width: 320px;
}

img {
  width: 100%;
  height: 100%;
}
<div id="test-div">
  <img src="https://u01.appmifile.com/images/2017/10/27/467720b2-5023-4460-864a-cd2dde58ee3b.jpg">
</div>

最佳答案

尝试使用此代码,希望对您有用。

var wid = document.getElementById("test-div").offsetWidth;
var hei = (wid) * 9 / 16;
document.getElementById("test-div").style.height = hei+'px';
#test-div {
  width: 400px;
}
img {
  width: 100%;
  height: 100%;
}
<div id="test-div">
  <img src="https://u01.appmifile.com/images/2017/10/27/467720b2-5023-4460-864a-cd2dde58ee3b.jpg">
</div>

这是使用 max-width 而不是 width 的演示。

var wid = document.getElementById("test-div").offsetWidth;
var hei = (wid) * 9 / 16;
document.getElementById("test-div").style.height = hei+'px';
#test-div {
  max-width: 400px;
}
img {
  width: 100%;
  height: 100%;
}
<div id="test-div">
  <img src="https://u01.appmifile.com/images/2017/10/27/467720b2-5023-4460-864a-cd2dde58ee3b.jpg">
</div>

谢谢你...

关于javascript - 通过 Javascript 分配 CSS 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58834552/

相关文章:

jquery - 带有 MouseOver Zoom 的垂直旋转木马

html - 如何在另一个 div 中对齐 3 个 div(左/中/右)?

javascript - React : Component with just a form, 表单提交操作因组件的使用者而异

javascript - HTML5 验证在 OnChange 选择框表单上不起作用 提交

Jquery 切换每个具有相同 id 的 div

jquery - 您好,这通常可以只显示 html-url 中的一个 div 吗?

css - Vue datetimepicker - 月 View 仅显示 1 行

javascript - 读取函数内另一个 if 条件中变量的值

javascript - IF && 语句 Javascript

javascript - 如何使 'None selected' 不适用于下拉菜单的更改