简体   繁体   中英

Why does the value of width gets set to zero when the page is refreshed in chrome?

I wrote some jQuery code in which I was getting the width of images on screen and storing them in a variable. Then I logged that variable in the console to see it's value. When the page loads for the first time, it displays correct value, however if I press F5, it displays 0 as the width.

Here's the HTML:

    <body>
        <img src="img1.jpg" alt="image">
        <img src="img1.jpg" alt="image">
        <script type="text/javascript" src="script.js"></script>
    </body>

Here's the jQuery code (script.js) :

    jQuery(document).ready(function($) {
        var imgs = $('img');
        var width = imgs[0].width;
        console.log(width);
    });

The console displays 600 when the page is loaded for the first time but when I press F5 it displays 0 . Why is it so?

At jQuery(document).ready() time, there is no guarantee that images are loaded yet. Images must be loaded in order to get their width. Images are loaded asynchronously and may finish after jQuery(document).ready() fires.

To know for sure that an image is loaded, you either need to have an onload handler for that specific image so you can know when it is specifically loaded or you need to only inspect the image widths when all the images in the page are loaded with window.onload or in jQuery $(window).load(fn) .

The simplest thing to do would be to change your code to this:

jQuery(window).load(function() {
    var imgs = jQuery('img');
    var width = imgs[0].width;
    console.log(width);
});

Personally, I would recommend that you use jQuery's .height() and .width() methods like this:

jQuery(window).load(function() {
    var imgs = jQuery('img');
    var width = imgs.eq(0).width();
    console.log(width);
});

You can see this one work here: http://jsfiddle.net/jfriend00/D4CyN/

If you know the image dimensions, put them in the markup:

<img src="img1.jpg" width="600" height="…">

Then you'll never get a 0 width. :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM