How to get real image width & height (cross browser) by JavaScript function ?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
First of all, you have a greater chance of getting your question answered if you'd just ask it in a more polite way, and supplying as much relevant information as possible.
Anyway...
For as far as I know, you can use the .width
property across pretty much all browsers:
function getDimensions(id) {
var element = document.getElementById(id);
if (element && element.tagName.toLowerCase() == 'img') {
return {
width: element.width,
height: element.height
};
}
}
<img id="myimage" src="foo.jpg" alt="" />
// using the function on the above image:
var dims = getDimensions('myimage');
alert(dims.width); --> shows width
alert(dims.height); --> shows height
回答2:
var realWidth = $("#image").attr("naturalWidth");
var realHeight = $("#image").attr("naturalHeight");
回答3:
Yay, Google!
There's a few ways to do this depending on exactly what you need (which you have unhelpfully omitted to include). Probably the simplest in a general sense is to get a reference to the Image object and inspect the width
and height
properties.
回答4:
jquery + <img src="" ... id="hello" />
+ $("#hello").width()