admin管理员组

文章数量:1289911

I'm having a hard time picking up how to grab the dimensions of an element with jQuery. Here is my sample code:

$(document).ready(function() {
        var width = $("#image_1").width();
        var height = $("#image_1").height();
        document.write(width);
        document.write(height);
    });  

Now of course I have an image with an id of #image_1. What happens when I try to run it is that it outputs two zeros. Not null twice, or undefined twice.

Thanks for the help from a javascript newb.

I'm having a hard time picking up how to grab the dimensions of an element with jQuery. Here is my sample code:

$(document).ready(function() {
        var width = $("#image_1").width();
        var height = $("#image_1").height();
        document.write(width);
        document.write(height);
    });  

Now of course I have an image with an id of #image_1. What happens when I try to run it is that it outputs two zeros. Not null twice, or undefined twice.

Thanks for the help from a javascript newb.

Share Improve this question asked Feb 27, 2009 at 3:52 patricksweeneypatricksweeney 4,0227 gold badges44 silver badges56 bronze badges 1
  • In addition, the image does not appear in the source. – patricksweeney Commented Feb 27, 2009 at 4:23
Add a ment  | 

4 Answers 4

Reset to default 8

Even though you've already chosen an answer, I am typing this one so you understand why your prior code did not work.

jQuery's document.ready function fires before images are loaded. Use window.load instead...

$(window).load(function() {
  var width = $("#image_1").width();
  var height = $("#image_1").height();
  document.write(width);
  document.write(height);
});

For what it's worth, I think it is better to use jQuery for this task because of the inherent cross-browser functionality.

Perhaps this was a typo in your question, but is the ID of your image really "#image_1"? For your code to work, it should be just "image_1". The "#" is only used in the jquery selector to specify that the text following it is an ID.

You may get 0 for the width and height if the image is not visible. (That's what just happened to me.)

Updated: You can confirm that the image is added to the DOM by checking the length property of the jQuery object:

var inDOM = ($('#image_1').length > 0);

This works for me:

<head>
    <script type="text/javascript">
        function foo() {
            var image = document.getElementById("the_image");
            alert(image.offsetWidth);
            alert(image.offsetHeight);
        }
    </script>
</head>
<body onload="foo();">
    <img src="img.png" id="the_image">
</body>

This works as long as the image is not set to display: none; Using offsetWidth and offsetHeight also has the advantage of not requiring jQuery, at all.

本文标签: aspnetHaving problems with grabbing image dimensions with jQueryStack Overflow