[英]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. 我正在尝试使用JavaScript / jQuery将width和height属性从一个元素复制到另一个元素,但是无法实现。
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 : 用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.
您应该有一个使div适应图像的CSS。
You can access the .width
and .height
properties of the image element directly. 您可以直接访问图像元素的
.width
和.height
属性。
Divs don't have those properties, so you have to use CSS to set them: Divs没有这些属性,因此您必须使用CSS进行设置:
var img = $('#one').get(0);
$('#two').css({ width: img.width, height: img.height });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.