admin管理员组

文章数量:1024614

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

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

本文标签: javascriptSetting the stylemaxWidth from a variableStack Overflow