jquery image width() is not returning correct value in IE9
We have an image tag with width and height specified as auto so that we can get the width and height of the actual image. So we use the following to get them.
$("img.list-image").width()
$("img.list-image").height()
in FF, Chrome, IE8 and safari, the width and height returned are 125 pixel and 160 pixel respectively and these values are correct. But in IE9, the width is 1519 pixels and the height is 771 pixels. For some reason, these width and height functions are not returning proper values in IE9. Any help is appreciated.
EDIT: Following is the code We are using
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Image Page</title>
<style type="text/css" >
.list-category-image
{
border-width: 0px;display:none;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
//<![CDATA[
$(function() {
categoryImageaspectratio();
});
function categoryImageaspectratio() {
$("img.list-category-image").one('load', function() {
var width = 85.0, height = 85.0;
var realWidth, realHeight;
realWidth = $(this).width(); // Note: $(this).width() will not
realHeight = $(this).height();
//alert("width, height = (" + realWidth + "," + realHeight + ")");
// Now scale the image.
var aspectRatio = 1.0;
if (realHeight / height > realWidth / width) {
aspectRatio = realHeight / height;
width = realWidth / aspectRatio;
}
else {
aspectRatio = realWidth / width;
height = realHeight / aspectRatio;
//alert("aspectRatio = " + aspectRatio);
//alert("height = " + height);
}
var imgWidth = parseInt(width) + "px";
var imgHeight = parseInt(height) + "px";
//alert(imgWidth + ", " + imgHeight);
// $(this).css("width", imgWidth).css("heigth", imgHeight).css('di开发者_运维技巧splay', 'block');
$(this).css("width", imgWidth).css("heigth", imgHeight).css('display', 'block').css('text-align', 'center').css('margin-left', 'auto').css('margin-right', 'auto');
}).each(function() {
if (this.complete) {
$(this).load();
}
});
}
</script>
</head>
<body>
<div style="width:85px; height:85px;">
<img class="list-category-image" src="http://ecx.images-amazon.com/images/I/411j0fCdVKL._SL160_.jpg" alt="" />
</div>
</body>
</html>
using this keyword is always very tricky and sometimes confusing, it can be different values in different implementations of javascript. try to define your image as a variable to see if it fixes your problem:
var imgList = $("img.list-category-image");
imgList.one('load', function() {
var width = 85.0, height = 85.0;
var realWidth, realHeight;
realWidth = imgList.width(); // Note: $(this).width() will not
realHeight = imgList.height();
you can use the following code to check what the type of this is:
alert(typeof(this));
精彩评论