【发布时间】:2012-08-28 14:21:19
【问题描述】:
已解决:语法错误
以下代码有效:
var image = {width:0,height:0};
var imageObject = new Image();
function getImageSize(id) {
imageObject.src = id.attr("src");
image.width = imageObject.width;
image.height = imageObject.height;
}
原始问题
我想获取图像的原始宽度和高度,并尝试了不同的代码来实现它。我的函数在点击事件时触发,所有图像都调整为 400x300。
我尝试使用 auto 将图像调整为原始大小:
var image = {width:0,heigth:0};
function getImageSize(id) {
id.css({
'width': 'auto',
'heigth': 'auto'
});
image.width = id.attr('width');
image.heigth = id.attr('heigth');
}
附加auto 并没有改变图像的大小。
alert(id.attr('width')); 总是返回“未定义”。所以它不起作用
var image = {width:0,heigth:0};
var imageObject = new Image();
function getImageSize(id) {
imageObject.src = id.attr("src");
image.width = imageObject.width;
image.heigth = imageObject.heigth;
}
alert(image.width); 完美运行。
alert(image.heigth); 返回未定义。
使用imageObject.naturalWidth 与上面的一样 - 正确给出了宽度,但未定义高度。
我读到您必须附加新的图像对象,但是当我使用 imageObject.appendTo('body'); 时,我什至无法单击图像。
感谢您的任何建议。
【问题讨论】:
-
一旦你改变了图像大小,自动不会再把它带回来。至于获取图片的大小,必须先加载。
-
image.heigth语法错误:“高度” -
哦,我写错了很多次,改变语法解决了它