画像のオリジナルサイズをJavaScriptで取得する
getNaturalSizeにimageオブジェクトを投げてあげるとオブジェクトが返る。
var cache = [];
var getNaturalSize = (function(){
if(Image.naturalWidth || Image.naturalHeight){
return function(image){
return {
"width" : image.naturalWidth,
"height" : image.naturalHeight
};
}
}
else if(window.opera){
return function(image){
if(!cache[image.src]){
var mem = {
"w": image.width,
"h": image.height
};
image.removeAttribute("width");
image.removeAttribute("height");
w = image.width;
h = image.height;
image.width = mem.w;
image.height = mem.h;
cache[image.src] = {
"width" : w,
"height" : h
};
}
return cache[image.src];
};
}
else if(window.attachEvent){
return function(image){
if (image[key] && image[key].src === image.src) {
return image[key];
}
run = image.runtimeStyle;
mem = {
"w" : run.width,
"h" : run.height
}; // keep runtimeStyle
run.width = "auto"; // override
run.height = "auto";
w = image.width;
h = image.height;
run.width = mem.w; // restore
run.height = mem.h;
image[key] = {
"width" : w,
"height" : h,
"src" : image.src
};
return image[key]; // bond
}
}
else{
return function(image){
return {
"width" : 100,
"height" : 100
};
}
}
})();
Firefox、IE6~8、Chrome、Operaで動作する。Safari未検証。
トラックバック URL :
コメント (0)