IE图像宽度&下载图像之前高度 = 0
我正在尝试设置宽度和宽度我在 javascript 中创建的图像元素的 height 属性。在 FF、Opera & Chrome 它设置宽度和宽度高度正确。然而在 IE 6 和 IE 中7(还没试过8)宽度和宽度下载图像之前,高度保持为 0。我需要这个的原因是这样我可以将每个图像放置在行和行中。 cols 基于其当前大小。
如果无法设置宽度和宽度, IE 中的高度属性 我想我只需要创建自己的自定义属性并将其设置在那里。
这是我用来创建和创建的基本代码注入元素。
var img = document.createElement('img');
var wrap = document.createElement('div');
document.body.appendChild(wrap);
wrap.appendChild(img);
img.src = 'blah.jpg';
img.width = '100';
img.height = '100';
img.style.display = 'none';
// IE: width: 0 | height: 0
// FF: width: 100 | height: 100
alert('width: ' + img.width + ' | height: ' + img.height);
编辑:
我尝试设置 img.style.visibility = 'hidden' 而不是 img.style.display='none';但这没有什么区别。
编辑
我发现了这个问题。实际问题是 Aziz 解决方案和我在原始示例中遗漏的内容的组合。看来在 IE 中,如果在分配宽度和宽度之前将元素附加到另一个元素中, height IE 只是忽略它。
I'm trying to set the width & height property of an image element i've created in javascript. In FF, Opera & Chrome it's sets the width & height correctly. However in IE 6 & 7 (Haven't tried 8) the width & height remain 0 until the image is downloaded. The reason I need this is so that i can position each image in rows & cols based on it's current size.
If it's not possible to set the width & height properties in IE I think i'll just have to create my own custom property and set it in there.
Here is the basic code i'm using to create & inject the element.
var img = document.createElement('img');
var wrap = document.createElement('div');
document.body.appendChild(wrap);
wrap.appendChild(img);
img.src = 'blah.jpg';
img.width = '100';
img.height = '100';
img.style.display = 'none';
// IE: width: 0 | height: 0
// FF: width: 100 | height: 100
alert('width: ' + img.width + ' | height: ' + img.height);
EDIT:
I've tried setting img.style.visibility = 'hidden' instead of img.style.display='none'; but it doesn't make a difference.
EDIT
I found the issue. The actual problem was a combination of Aziz solution and something I left out in the original example. It appears that in IE if you append the element inside another element before assigning a width & height IE just ignores it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里解释了此问题
为了在IE中获得正确的尺寸,需要设置
display:hidden
visibility:hidden
。但是,您必须确保仅当浏览器是 IE 时才设置它。编辑
试试这个(对我有用)
This problem is explained here
In order to get the correct dimensions in IE, you need to set
display: hidden
visibility: hidden
. However, you have to make sure you set it only if the browser is IE.Edit
try this (works for me)
您将需要单位:
请记住添加单位“px”。分别使用
element.style.width
和element.style.height
代替element.width
和element.height
为了跨浏览器兼容性。You will need the unit:
Remember to add the unit "px". Use
element.style.width
andelement.style.height
instead ofelement.width
andelement.height
respectively for cross browser compatibility.