简体   繁体   English

设置一个元素宽度等于另一个

[英]Set one element width equal to another

I'd like to set the div width equal to the image width.我想将 div 宽度设置为等于图像宽度。 Here's what I can think of:这是我能想到的:

<script type="text/javascript">
window.onload = function ()
{
document.getElementById('foo').style.width = document.getElementById('bar').width + 'px';
}
</script>
<div id="foo" style="background:red;"><img id="bar" src="image.jpg"></div>

It seems to be working, but I'm not sure if it's correct coding.它似乎正在工作,但我不确定它是否是正确的编码。

Thanks in advance for checking the code or any improvement you suggest!提前感谢您检查代码或您建议的任何改进!

Rain lover雨情人

You shouldn't have to specify a width for the div.您不必为 div 指定宽度。 You can give the parent div a float value.您可以给父 div 一个浮点值。

http://jsfiddle.net/46JTb/ http://jsfiddle.net/46JTb/

But if you want it to truly be the same value, I believe your method will suffice.但是,如果您希望它真正具有相同的值,我相信您的方法就足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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