2012-09-03 56 views
7

解决:语法错误

下面的代码工作:如何获得图像的原始尺寸-Jquery

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的工作方式如上 - 宽度给定正确,但heigth未定义。

我读过,你必须追加新的图像对象,但是当我使用imageObject.appendTo('body');我甚至不能点击图像。

感谢您的任何建议。

+0

一旦你改变图像大小,自动将不会再次把它。至于获取图像的大小,它必须先加载。 – adeneo

+0

'image.heigth'语法错误:“高度” –

+0

哦,我写错了很多次, 更改语法解决了它 – CadanoX

回答

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");