简体   繁体   中英

Copy certain values from one element to another

I'm trying to copy the width and height attributes from one element to another with JavaScript/jQuery but can't implement it.

I have something like that:

<div id="two">

<img src="picture.jpg" id="one" width="600px" height="300px" />

</div>

and I want to get this:

<div id="two" width="600px" height="300px" >

<img src="picture.jpg" id="one" width="600px" height="300px" />

</div>

With jquery :

var $one = $('#one');
$('#two').attr('width', $one.attr('width'))
.attr('height', $one.attr('height'));

But usually that's wrong. You should have a css that adapts the div to your image.

You can access the .width and .height properties of the image element directly.

Divs don't have those properties, so you have to use CSS to set them:

var img = $('#one').get(0);
$('#two').css({ width: img.width, height: img.height });

I'd suggest, without greater information:

var el = $('#two'),
    img = el.find('img');

el.css({'height' : img.height(), 'width' : img.width()});

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM