javascript - Setting the style.maxWidth from a variable - Stack Overflow

My cod is this:<img src="img.png"><dd id="123">COMMENT<dd><sc

My cod is this:

<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>

This alerts a window with width of an img.png. The question is: how to set this width value for an element I need.

Something like:

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

Instead of:

alert(this.width);

My cod is this:

<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>

This alerts a window with width of an img.png. The question is: how to set this width value for an element I need.

Something like:

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

Instead of:

alert(this.width);
Share Improve this question edited Jan 7, 2016 at 15:34 Will Vousden 33.4k9 gold badges88 silver badges97 bronze badges asked Jan 7, 2016 at 15:32 ХомичусХомичус 332 silver badges8 bronze badges 1
  • 2 document.getElementById('123').style.maxWidth = this.width; So what happened when you tried that? – Frédéric Hamidi Commented Jan 7, 2016 at 15:33
Add a ment  | 

1 Answer 1

Reset to default 3

The width DOM property of an image is going to be a number.

The CSS max-width property only accepts a length as its value.

You need to add units to your number.

= this.width + "px";

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745621746a4636559.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信