从变量中设置style.maxWidth

Setting the style.maxWidth from a variable

本文关键字:style maxWidth 设置 变量      更新时间:2023-09-26

我的代码是:

<img src="img.png">
<dd id="123">COMMENT</dd>
<script>
var img = new Image();
img.onload = function () {
alert(this.width);
}
img.src = 'img.png';
</script>

这会提醒一个宽度为img.png的窗口。问题是:如何为我需要的元素设置这个宽度值。

类似于:

document.getElementById('123').style.maxWidth = this.width;

代替:

alert(this.width);

图像的widthDOM属性将是一个数字。

CSS max-width属性只接受长度作为其值。

你需要在你的数字中添加单位。

= this.width + "px";