如何获得图像的原始大小-Jquery

Cad*_*noX 7 jquery height width

求助:语法错误

以下代码有效:

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;
}
Run Code Online (Sandbox Code Playgroud)

原始问题

我想获得图像的原始宽度和高度,并尝试使用不同的代码来实现它.我的功能触发点击事件,所有图像都调整为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');
}
Run Code Online (Sandbox Code Playgroud)

附加auto没有改变图像的大小.

alert(id.attr('width'));总是返回'undefined'.所以它不起作用

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;
}
Run Code Online (Sandbox Code Playgroud)

alert(image.width); 工作得很好.

alert(image.heigth); 返回undefined.

使用imageObject.naturalWidth上面的工作 - 正确给出宽度但未定义高度.

我读到你必须追加新的图像对象,但是当我使用时我imageObject.appendTo('body');甚至无法点击图像.

谢谢你的任何建议.

Tra*_*s J 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>
Run Code Online (Sandbox Code Playgroud)

另一种方法是删除已应用的样式:

myImg.removeAttribute("style");
Run Code Online (Sandbox Code Playgroud)