如何使用Jquery获取图像的原始尺寸

7

已解决: 语法错误

下面的代码是有效的:

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');时,甚至无法单击该图像。

感谢任何建议。


一旦更改了图像大小,auto 将不会再将其恢复。至于获取图像的大小,必须先加载它。 - adeneo
image.heigth 语法错误:"height"。 - Travis J
哦,我写错了很多次,改变语法解决了它。 - CadanoX
1个回答

2
这是一个简单的包含示例,用于替换图像,并在修改后保持其原始大小。
<img src="http://www.finesttreeserviceaz.com/wp-content/uploads/2012/02/tree2.gif" id="bar" />
<script type="text/javascript">
    var myImg = document.getElementById("bar");
    myImg.setAttribute("style", "width:400px;height:300px;");
    function resetBar() {
        var newImg = new Image();
        var oldImage = document.getElementById("bar");
        newImg.src = oldImage.src;
        oldImage.parentNode.replaceChild(newImg, oldImage);
    }
    setTimeout("resetBar();", 2000);
</script>

另一个选择是移除应用的样式:

myImg.removeAttribute("style");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接