开发者

HTML image loading problem

I have a site where I have to dynamically load images. I must know their width/height before laying them down, so I am using the onload event handler. What I found anyway, is that sometimes those values are 0/0 even in the handler (this happens on Chrome and as I am targeting webkit, this is the browser to use). Is there any way to enforc开发者_如何转开发e this? I mean I could use some things like a setTimeout in the case the image is 0/0 and recheck until its done, what I'm looking for is something more clean and possibly using DOM methods...


You're using the onload event of the image right? If that's not reliable, I'd try writing the image into the DOM in a hidden element and then getting it's dimensions.


I'm not entirely sure about what you want to achieve. The only reason I can imagine why you would need the image width and height is if you don't want to scale the image. This seems kinda unlikely because it would not make for a clean layout of your page.

If you simply want to preserve aspect ratio, set the images to a certain height and then leave height on auto (e.g. in a CSS class):

 .myImg {
     /* ... */
     width: 150px ;
     height: auto ;
     /* ... */
 }

This way you will have a clean layout preserving the aspect ratio of your images while not having to use scripts to modify their width and height. Images in HTML preserve aspect ratio by default.

HTH


is the onload event in the head of your page? I had before some problems when it stands it in the head.

You can also put your javascript before the end of the body. In that case you don't need the onload event.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜